Hi,
I’m trying to create a program that allows the user to move a car with the up down right and left arrow keys.
I want the up and down keys to accelerate backwards and forwards.
I want the left and right keys to control direction of movement so that the car rotates and points where its headed.
I’m trying to write this in an object oriented fashion and use PVectors.
So far I have the car moving but the controls are extremely awkward. Also it seems keyPressed and keyReleased can’t be placed in the Input class - it seems processing only calls them if they are after draw in the main sketch program. Seems strange.
I’d appreciate any advice. Here is my code:
Main class:
Vehicle vehicle;
Input input;
void setup() {
size(640, 480);
input = new Input();
vehicle = new Vehicle(input);
}
void draw() {
background(0);
vehicle.applyForce();
vehicle.display();
}
void keyPressed() {
int code = keyCode;
switch(code) {
case 38:
input.up = true;
break;
case 40:
input.down = true;
break;
case 39:
input.right = true;
break;
case 37:
input.left = true;
break;
}
}
void keyReleased() {
int code = keyCode;
switch(code) {
case 38:
input.up = false;
break;
case 40:
input.down = false;
break;
case 39:
input.right = false;
break;
case 37:
input.left = false;
break;
}
}
INPUT CONSTANTS CLASS:
class Input {
boolean up = false;
boolean down = false;
boolean left = false;
boolean right = false;
}
VEHICLE CLASS
class Vehicle {
PVector location;
PVector velocity;
PVector acceleration;
PImage image;
Input input;
int topSpeed = 1;
Vehicle(Input input) {
this.image = loadImage("player1car.png");
this.input = input;
this.location = new PVector(width/2, height/2);
this.velocity = new PVector(0,0);
this.acceleration = new PVector(0.0,0.0);
}
void applyForce() {
// get the acceleration
if(input.up) {
acceleration.y -= 1;
println("up");
}
if(input.down) {
acceleration.y += 1;
println("down");
}
if(input.right) {
acceleration.x += 1;
println("right");
}
if(input.left) {
acceleration.x -= 1;
println("left");
}
velocity.add(acceleration);
velocity.limit(topSpeed);
location.add(velocity);
velocity.mult(0);
}
void display() {
image(image, location.x, location.y);
}
}
Thanks for your help,
Marc