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

2015/1/24

Collision

drago drago

2015/1/24

#
I need a simple collision code I have Tank and wall2 as actors I have no code yet as I have no idea how to do it please help
danpost danpost

2015/1/25

#
How the tank moves would be a big consideration in how to code collision with obstacles. If your tank only had two-way movement, it would be simple; however, even with four-way movement, things get somewhat complicated if the image of the tank is not square (the length of the sides may have to be odd, as well). Then, with universal movement (along any degree of rotation), the turning itself adds that same dimension of complexity regardless of the image being square or not. Each action, turning and moving, must have its own collision checking using one of the Actor class methods that are provided to determine intersection with other objects.
drago drago

2015/1/25

#
this is the code for it { if (Greenfoot.isKeyDown("left")) { turn(-3); } if (Greenfoot.isKeyDown("right")) { turn(3); } if (Greenfoot.isKeyDown("up")) { move(-2); } if (Greenfoot.isKeyDown("down")) { move(2); }
danpost danpost

2015/1/25

#
After the left and right key checks for turning, you need to perform collision checking. Then again, after the up and down key checks for moving. However, hard-coding the values to turn and move by in no way allows you to know how to revert a turn or move or even if any way made (although, if a collision is found, most likely it was due to the turning or moving -- but still, you would not know if it was due to a left or right turn or a forward or backward movement). Set up local int variables for the direction of turning and for the direction of movement and adjust them dependent on the keys found down. Then, do the action, perform the collision checking and revert the action if collision was found. For example, the turning portion could be something like this:
int dr = 0; // direction of rotation
if (Greenfoot.isKeyDown("left")) dr--;
if (Greenfoot.isKeyDown("right")) dr++;
if (dr != 0)
{
    turn(3*dr);
    //  check for intersecting obstacles and 'turn(-3*dr)', taking the turn back, if any are found
}
You need to login to post a reply.