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

2014/4/14

How to make an object not move if it touches another object? (Beginner)

name68 name68

2014/4/14

#
Hello, I am absolutly a beginner with Greenfoot. In the programm, theres a wombat. If the wombat comes to a tent, it shouldn`t be able to move. Could please someone tell me the code I have to use for this?
1
2
3
4
if(protected boolean intersects(Tent.class))
{
    move(0)
}
This somehow does not work and maybe makes no sense...
danpost danpost

2014/4/14

#
Do not create new code to not do what you do not want to do. Put a condition on the code that does what you do not want to do. In other words, instead of 'do not move if intersecting a tent', use 'move only if not intersecting a tent'. You probably already have movement code in your class. Just restrict when it can execute that code.
name68 name68

2014/4/14

#
Do you mean something like this?
1
2
3
4
if(protected boolean intersects(Tent.class)!= null)
{
    move(2)
}
danpost danpost

2014/4/14

#
In your code snippet above, you wrote:
1
if (protected boolean intersects(Tent.class))
'protected boolean' describes the accessibility and return type of the method and should not be included with the calling of the method. The line should simply be the following:
1
if (intersects(Tent.class))
which is equivalent to 'if (intersects(Tent.class) == true)' or, the opposite being:
1
if (!intersects(Tent.class))
which is equivalent to 'if (intersects(Tent.class) == false)'.
danpost danpost

2014/4/14

#
Again, this:
1
if (intersects(Tent.class) != null)
A boolean value, that which the 'intersects' method returns, is never null.
name68 name68

2014/4/14

#
If I write
1
2
3
4
if(!intersects(Tent.class))
       {
           move(2);
       }
Then I get a message incompatible types:java.lang.Class<Tent>cannot be converted to greenfoot Actor. But I saved the Tent as an Actor. Can you help me?
danpost danpost

2014/4/14

#
Looks like I continued with your bad (I was more concerned with the 'private boolean' part). 'Tent.class' is a reference to a class, not an Actor and the 'intersects' method requires an Actor object. You probably want to use the 'isTouching' method instead, which checks for any object of the given class (instead of a specific object):
1
if (isTouching(Tent.class))
name68 name68

2014/4/14

#
Thank you much! You did help me really much.
You need to login to post a reply.