NSD
NSD

Reputation: 13

Car is not moving right?

enter image description hereCar is moving but as it reaches column 5 it stops there and does not move.

Car has the move() method, in which Car instances drive forwards with the amount of cells equivalent to speed in each time step (from left to right).

Car shall accelerate its speed by 1 after each time step and the speed for the next time step will be higher

public class Car extends Actor {

        public  final int MAXSPEED= 5;
        private int speed = 3;


        public void move() {
            Grid<Actor> gr = this.getGrid();
            if (gr != null) {
                Location loc = this.getLocation();
                Location next = new Location(0,this.speed);
                if (gr.isValid(next)) {
                    this.moveTo(next);
                } else {
                    this.removeSelfFromGrid();
                }
            }
        }

 public void accelerate(){

            if (this.speed <5) {
             //   move();
                this.speed++;
            } else {
                this.speed = MAXSPEED;
            }
        }

        public void dawdle(){

            if(Math.random() <= 0.3){

               this.speed= speed--;

            }else{
                this.speed=speed;
            }


        }


  public Car(){

            if (speed==1){
                this.setColor(Color.red);
            }
            else if (speed==5){
                this.setColor(Color.green);
            }
    }

  


    @Override
    public void act(){

            this.move();
           this.accelerate();
           this.dawdle();
    }
}

Upvotes: 0

Views: 107

Answers (2)

NSD
NSD

Reputation: 13

To move the car i needed the car current position so speed can be added into the current position to move the car.

Location next = new Location(loc.getRow(),loc.getCol()+this.speed);

Upvotes: 0

queeg
queeg

Reputation: 9473

Your accelerate function allows the car to have a maximum speed of 5. Together with your move function, which contains

 Location next = new Location(0,this.speed);

the car will never go beyond position 5. I think you know what needs to be changed:

newlocation = currentLocation + speed

I do not see anything like this in your code.

Upvotes: 1

Related Questions