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

2015/1/31

adding/subtracting integers?

h123n h123n

2015/1/31

#
Hi! I have been creating a game in which you have a motionX and a motionY and when you hold down left, X will go down meaning the person will keep moving left. What I can't understand is how my program doesn't appear to subtract the motionX value. Here is my code:
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
import greenfoot.*;
 
/**
 * Write a description of class Person here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Person extends Actor
{
    int MotionX = 0;
    int MotionY = 0;
    /**
     * Act - do whatever the Person wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
 
    public void act()
    {
        setLocation( getX() + MotionX , getY() ) ;
        if (Greenfoot.isKeyDown("left"))
        {
            int sum = MotionX -1;
        }
    }   
}
NikZ NikZ

2015/1/31

#
You never use sum. MotionX stays the same when you create a new variable like in 23. Use MotionX--;
h123n h123n

2015/1/31

#
thanks, how would I minus 2 instead of 1?
Super_Hippo Super_Hippo

2015/1/31

#
Use -=2 instead of -- then. Use the setLocation at the end. If you just want him to move if you click and don't move it when you don't click it, then you don't need the fields.
1
2
3
4
5
6
7
8
9
10
11
public class Person extends Actor
{
    public void act()
    {
        int motionX=0; //,motionY=0;
        
        if (Greenfoot.isKeyDown("left")) motionX-=2;
 
        setLocation( getX() + motionX , getY() ) ;
    }   
}
h123n h123n

2015/1/31

#
Thanks! sorry for being a total noob, I am trying to make a physics engine
You need to login to post a reply.