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

2012/2/22

Drop ball then turn at edge of world randomly

Tomc84 Tomc84

2012/2/22

#
Hello all, I'm having trouble making my ball turn at the edge randomly all it wants to do is rotate the object. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Ball here. * * @author (your name) * @version (a version number or a date) */ public class Ball extends Actor { private int deltaY = 2; private int deltaX = 2; /** * Act - do whatever the Ball wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { setLocation(getX() , getY() +deltaY);// Add your action code here. if (atWorldEdge()) { deltaY = deltaY * (-1); setLocation(getX() +deltaX, getY() ); //turn(Greenfoot.getRandomNumber(90)+20); // rotate object not turn //setRotation(Greenfoot.getRandomNumber(50)); } } /** * Test if we are close to one of the edges of the world. Return true is we are. */ public boolean atWorldEdge() { if(getX() < 20 || getX() > getWorld().getWidth() - 20) return true; if(getY() < 20 || getY() > getWorld().getHeight() - 20) return true; else return false; } }
Morran Morran

2012/2/23

#
You want the ball to turn, and not rotate? You are using the "setLocation(int newX, int newY)" method to move your ball. setLocation() moves your ball in an absolute way. It doesn't care which direction your ball is facing in, it will still move it in the same way. I think that what you want is the "move()" method, which is in the "Animal" class I think. Just make Ball extend Animal instead of Actor, and use "move()" instead of "setLocation()". I hope this helps!
You need to login to post a reply.