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

2011/12/10

Actor teleporting

darkmist255 darkmist255

2011/12/10

#
**solved** I am making an actor called "Stalker" that just slowly moves closer and closer to the player, damaging on contact. It is working mostly okay, but is teleporting randomly. Not to random locations however; it teleports itself to the X or Y coordinate of the player (a perfect line vertical or sideways from the player) then continues moving as normal from there, until teleporting again. This is the code for the stalker
public class Stalker extends GroundMover
{
    Room room;
    Stats stats;
    Character character;
    
    double moveSpeed = 1;
    double yMomentum, xMomentum = 0;
    
    public void addedToWorld(World world)
    {
        room = (Room)getWorld();
        stats = room.stats;
        character = room.character;
    }
    
    public void act() 
    {
        findPlayerAndMove();
        detectCollision((int)moveSpeed, (int)xMomentum, (int)yMomentum); //this is a method in the superclass (what this is a subclass of). No problems with it
    }    
    
    public void findPlayerAndMove()
    {
        xMomentum = (character.getX() - getX());
        yMomentum = (character.getY() - getY());
        
        //determine which direction to move
        if(Math.abs(xMomentum) > Math.abs(yMomentum))
        {
            yMomentum = 0;
        }
        else if(Math.abs(yMomentum) > Math.abs(xMomentum))
        {
            xMomentum = 0;
        }
        
        if(yMomentum > moveSpeed)
        {
            yMomentum = moveSpeed;
        }
        if(xMomentum > moveSpeed)
        {
            xMomentum = moveSpeed;
        }
        
        setLocation(((int)(getX() + xMomentum)), ((int)(getY() + yMomentum)));
    }
}
I've been trying to figure out why it only teleports every like 6 seconds, not just every single act() cycle. Once I know that, I think I can make it stop teleporting. Any help appreciated :D!
darkmist255 darkmist255

2011/12/10

#
Got it! I got rid of the direct link between distance and momentum. This is the working code:
public void findPlayerAndMove()
    {
        xDistance = (character.getX() - getX());
        yDistance = (character.getY() - getY());
        
        //determine which direction to move
        if(Math.abs(xDistance) > Math.abs(yDistance))
        {
            if(xDistance > 0) {
            xMomentum = moveSpeed; }
            else {
            xMomentum = -moveSpeed; }
            yMomentum = 0;
        }
        else if(Math.abs(yDistance) > Math.abs(xDistance))
        {
            if(yDistance > 0) {
            yMomentum = moveSpeed; }
            else {
            yMomentum = -moveSpeed; }
            xMomentum = 0;
        }
        
        setLocation(((int)(getX() + xMomentum)), ((int)(getY() + yMomentum)));
    }
You need to login to post a reply.