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

2014/1/20

how to make my character move left & right?

rash0078 rash0078

2014/1/20

#
here is my code: please focus on the code where i write " if greenfoor.iskeydown("left")) & and a couple of lines below. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * The person who will move about platforms. * @author - Michael "webmessia" */ public class Person extends Actor { //Basic Physics Variables private double positionX; private double positionY; private double velocityX = 0; private double velocityY = 0; private double accelerationX = 0; private double accelerationY = 0; //Force Values private double gravityY = 0.1; private double jumpForce = 3.5; private GreenfootImage _playerStart = new GreenfootImage ("Images/Idle/Idle_0.png"); private int speed = 2; public void addedToWorld(World w){ //We set our position to the position which we were added to the world at. positionX = getX(); positionY = getY(); } /** * 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() { //Apply Forces to change acceleration to move the person { if(Greenfoot.isKeyDown("right")) move(-30); if(Greenfoot.isKeyDown("left")) move(30); } applyGravity(); applyJumpForce(); //Basic Physics velocityX += accelerationX; velocityY += accelerationY; positionX += velocityX; positionY += velocityY; accelerationX = 0; accelerationY = 0; setLocation((int)positionX,(int)positionY); } /** * Accelerates the person downwards except for when they are on a platform */ private void applyGravity(){ // Check For collision with platform Actor coll = getOneIntersectingObject(Platform.class); if(coll == null){ //This is run when the person is not touching a platform //This code adds gravity to our total acceleration. accelerationY += gravityY; } else { //This is run once we hit a platform //We make our person stop moving in the y direction. (up/down direction). velocityY = 0; } } /** * Accelerates the person upwards if space is pressed and we are on a platform */ public void applyJumpForce(){ Actor coll = getOneIntersectingObject(Platform.class); if(coll != null){ //This is run when the person is touching a platform if(Greenfoot.isKeyDown("space")){ accelerationY -= jumpForce; } } } }
danpost danpost

2014/1/20

#
You are not adjusting your 'positionX' and 'positionY' fields when using 'move'.
You need to login to post a reply.