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

2018/4/13

Limit Rotation

Applez Applez

2018/4/13

#
Hey, im doing a school project and i chose to do a racing game, i have made a car with basic controls (turn left/right, move forwards/backwards) but i want to limit how much the car turns. The car is facing right, i want it to turn left 45 degrees and right 45 degrees (im guessing the angle i havent tried it out yet). Also, please tell me how to change the angle incase i want to. Please Help with this (Hopefully its danpost :) ) Thank You
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
 
/**
 * Write a description of class NSX4 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class NSX4 extends Actor
{
    /**
     * Act - do whatever the NSX4 wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        if (Greenfoot.isKeyDown("left"))
        {
            turn(-5);
        }
        if (Greenfoot.isKeyDown("right"))
        {
            turn(5);
        }
        if (Greenfoot.isKeyDown("up"))
        {
            move(5);
        }
        if (Greenfoot.isKeyDown("down"))
        {   
            move(-5);
        }
    }
}
danpost danpost

2018/4/13

#
It is unclear as to what you want exactly. It could be that you only want the car to go to the right, but it can also go up and down while going right; but not straight up or down and not at all to the left. I am not sure what else it could be; but it was not clearly stated as the way I said it could be.
TheGoldenProof TheGoldenProof

2018/4/13

#
Which direction is the car originally facing? for now I'll assume upwards. you can use the getRotation() method in combination with the Greenfoot.isKeyDown() to say 'if this key is down and its rotation is less or greater than this value, turn'
1
2
3
4
5
6
7
8
if (Greenfoot.isKeyDown("left") && getRotation() >= 225) //270 - 45 = 225
        {
            turn(-5);
        }
if (Greenfoot.isKeyDown("right") && getRotation <= 315) //270 + 45 = 315
        {
            turn(5);
        }
danpost danpost

2018/4/13

#
If as I thought it might be:
1
2
3
4
5
6
7
8
if (Greenfoot.isKeyDown("left") && getRotation() != 315)
{
    turn (-5);
}
if (Greenfoot.isKeyDown("right") && getRotation() != 45)
{
    turn(5);
}
Applez Applez

2018/4/13

#
Well dan's code worked! thank you! I guess theres no point explaining it now...
You need to login to post a reply.