This site requires JavaScript, please enable it in your browser!
Greenfoot back
aexelmaexel
aexelmaexel wrote ...

2019/2/11

Smooth movements

aexelmaexel aexelmaexel

2019/2/11

#
Im new to greenfoot and want to remake the mobile game "Twocars" but i have truble with the "smooth" movements of the cars
import greenfoot.*;
public class Blauesauto extends Actor
{
    boolean rightPressed = false;
    int Position = 0;
    int verschiebung = 88;

    public void act() 
    {
        if (rightPressed==false && Greenfoot.isKeyDown("right") && Position == 0)
        {
            nachlinks();
            Position = 1;
            rightPressed = true;
        } 
        if (rightPressed==false && Greenfoot.isKeyDown("right") && Position == 1)
        {
            nachrechts();
            Position = 0;
            rightPressed = true;
        }
        if(rightPressed==true && !Greenfoot.isKeyDown("right"))
        {
            rightPressed = false;
        }
        if( getOneIntersectingObject(Blauerkreis.class) != null)
        {

        }
    }    

    void nachlinks()
    {
        for ( int i = 0; i < verschiebung; i++)
        {

            setLocation(getX()-1,getY());
        }
    }
    int smoothlinkscounter= 0;
    
    void smoothnachlinks()
    {
        smoothlinkscounter++;
        if (smoothlinkscounter % 30 == 0)
        {
            setLocation(getX()-1,getY());
            turn(-1);
        }
    }

    void nachrechts()
    {
        for ( int i = 0; i < verschiebung; i++)
        {
            setLocation(getX()+1,getY());
        }
    }
}
danpost danpost

2019/2/11

#
This:
for (int i = 0; i < verschiebung; i++)
{
    setLocation(getX()+1,getY());
}
from the nachrechts method, is equivalent to this:
setLocation(getX()+verschiebung,getY());
A similar thing can be said for the loop in the nachlinks method. Instead of Position values of 0 and 1, it would be better to have Direction values of 1 and -1. Also, instead of a constant verschiebung value, you can have it decremented to zero during a move (setting it to 88 when a move is initiated). The multiple similar if statements can also be simplified. You would end up with something like this:
import greenfoot.*;

public class Blauesauto extends Actor
{
    boolean rightPressed;
    int direction = 1;
    int counter;
    
    public void act()
    {
        // initiating a move
        if (rightPressed != Greenfoot.isKeyDown("right"))
        {
            rightPressed = !rightPressed;
            if (counter == 0 && rightPressed)
            {
                counter= 88;
                direction = -direction;
            }
        }
        // moving
        if (counter > 0)
        {
            counter--;
            setLocation(getX()+direction, getY());
        }
    }
}
You need to login to post a reply.