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

2016/2/24

Help with Object Collision(It won't work :( )

af2akita af2akita

2016/2/24

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList; //ArrayList
/**
 * Write a description of class Bomber_Dog here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Bomber_Dog extends Actor
{
  int speed = 5;
  int value = 0;
  public void act() 
  {
    barrierDetection();
    obstacleDetection();
    wallDetection();
    checkKeys();
         
  }
    public void checkKeys()
    {
        if (Greenfoot.isKeyDown("w"))
        {
          setLocation(getX(), getY() - speed);
        }
        if (Greenfoot.isKeyDown("s"))
        {
           setLocation(getX(), getY() + speed); 
        }
        if (Greenfoot.isKeyDown("a"))
        {
           setLocation(getX()- speed, getY());
        } 
        if (Greenfoot.isKeyDown("d"))
        {
           setLocation(getX() + speed, getY());
        }
  }
  public  void barrierDetection()
  {
     Actor a = getOneIntersectingObject(Barrier.class);
     if(a != null)
     {
       setLocation(getX()-5, getY()-5);    
     }
  }
  public  void obstacleDetection()
  {
    Actor a = getOneIntersectingObject(Obstacle.class);
    if(a != null)
    {
     setLocation(getX()-5, getY()-5);     
    }
  }
  public  void wallDetection()
  {
    int x = getX();
    int y = getY();
    Actor a = getOneIntersectingObject(Wall.class);
    if(a != null)
    {
     setLocation(x,y);     
    }
  }
}
danpost danpost

2016/2/24

#
You should move -- and then check for collisions (you have 'checkKeys' last in your act method). Also, in the 'wallDetection' method, you are placing the actor in its current location (not moving it at all) when intersecting a wall.
af2akita af2akita

2016/2/25

#
I tried that, but the problem is that I can approach a block from the top and left, and it won't go through, but from the bottom or the right, I just phase through. :(
Super_Hippo Super_Hippo

2016/2/25

#
int dx=0, dy=0;
if (Greenfoot.isKeyDown("w")) dy--;
if (Greenfoot.isKeyDown("s")) dy++;
if (Greenfoot.isKeyDown("a")) dx--;
if (Greenfoot.isKeyDown("d")) dx++;
setLocation(getX()+speed*dx, getY()+speed*dy);
if (isTouching(Block.class) || isTouching(Obstacle.class)) setLocation(getX()-speed*dx, getY()-speed*dy);
This moves the actor and when it touches a block or other obstacle, it moves back to where it was. If you want the actor to move as near to the obstacle as possible, you can use the following instead of the last line:
for (int i=0; i<speed; i++)
{
    if (isTouching(Block.class) || isTouching(Obstacle.class)) setLocation(getX()-dx, getY()-dy);
    else break;
}
You need to login to post a reply.