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

2021/2/15

How to make the actor fall

lisi lisi

2021/2/15

#
so I took a tutorial on youtube and the guy made an object being solid and the other one fell on it, I did that and instead of one I putted two objects to be the "ground" in one worked very well, but the other object didn’t, I put the soil in a class and added two of them as a saying. In the video at some point he put two like I did and it worked normally, but the video its from 2012 i dont know if something changed and that's why it isnt working or if i didnt type the code wright MyWorld
    addObject(new Mouse(), 50, 50);
        
        addObject(new Wood(), 90,90);
        addObject(new Wood(), 430,270);
        
        addObject(new Cheese(), 545, 230);
actor Mouse:
public int speed= 5;
    public int vSpeed=0;
    private int aceleration=3;
    public void act(){
      keys();
      fall();
      checkFall();
    }
    
    public void checkFall(){
       if (onWood()){
         vSpeed=0;
        }
        else{
            fall();
        }
    }
    public boolean onWood(){
      Actor under =  getOneObjectAtOffset(0, getY()/2, Wood.class);
      return under != null;
    }
    
    public void fall(){
        setLocation(getX(), getY()+vSpeed);
        vSpeed = vSpeed + aceleration;
    }
    public void keys() 
    {
        if(Greenfoot.isKeyDown("left")){
            setLocation(getX()-speed, getY());
        }
        if(Greenfoot.isKeyDown("right")){ 
            setLocation(getX()+speed, getY());
        }
        if(isAtEdge()){
             getWorld().showText("You Lose", 300, 200);
             Greenfoot.stop();
        }
        if(isTouching(Cheese.class)){
            removeTouching(Cheese.class);
            getWorld().showText("You Win!", 300, 200);
            Greenfoot.stop();
        }
    }
}
danpost danpost

2021/2/15

#
Line 15 is an unchecked fall. I was expecting a position correction upon touching wood, not another fall if not. I would remove lines 14 thru 16 and lines 18 thru 21. Then change the checkFall method to:
private void checkfall()
{
    Actor wood = getOneIntersectingObject(Wood.class);
    if (wood != null)
    {
        int dir = (int)Math.signum(vSpeed);
        int dist = (wood.getImage().getHeight()+getImage().getHeight())/2+1;
        setLocation(getX(), wood.getY()-dir*dist);
        vSpeed = 0;
    }
}
lisi lisi

2021/2/16

#
Thanks! It works!
You need to login to post a reply.