PDA

View Full Version : Collision detection not working as expected


Nick
02-24-2007, 10:34 PM
Hello I hope someone here can help. I see a few other threads on collision and I thought I had it figured out after examining the flight simulator code with the rings, but I am using the same method as it and it is not working like I wanted it to.

In my attached program I have a tank that shoots a bullet when the user presses space. The bullet moves forward a set amount and then comes back to the tank. If the user aims right, it will go through a car. Also the car is always moving forward. I am using if {bullet} is within {5 meters} of {car} to detect a collision, but when shooting the bullet through the car this fails to trigger the expected action. What is strange is if I position the tank in front of the car and let the car run through the tank & bullet then the collision is detected.

I can't figure out why it works when the bullet is sitting still and does not work when the bullet moving. Is there something I'm missing?

DrJim
02-25-2007, 12:36 AM
Nothing wrong with your code - you just aren't testing for a hit rapidly enough. :(

Try having the tank move forward 2 meters every 0.25 sec. ( which will then also call world.collision every 0.25 sec.) The way you had it set up, you were only testing every 2 sec - world collision wasn't getting called again until after the tank completed moving 10 meters. (In a "do together" nothing happens again until all commands finish.)

I also tried slowing down the bullet to move 50 meters in 1.3 second (so it would move less than 10 meters in a quarter of a second}. Got nearly 100% collision detection - but not much fun as a game. :rolleyes: You'll need to play with the parameters some - but just make sure you have a reasonable chance of detecting a hit. (You might also try a while event based on the bullet being within 5 meters of the tank - that evaluates almost continuously.)

chuck
02-25-2007, 07:27 AM
Hello Nick,

I've found that events work well for collision detection, rather than using an IF instruction in a loop. The condition from the IF instruction can be used in an event of the type While something is true.

For your world, something like this this might work:

New Event:

While ( bullet is within 5 meters of policeCar ) is true
Begin: world.collision
During: Nothing
End: Nothing


In world.collision the IF command is then removed, and the method becomes an event hanlder to perform whatever functions you desire when a collision occurs. You can also fiddle with the 5 meters value to affect the "accuracy" of your collision.

I hope this helps.

By the way, why are you shooting at Police cars? Shouldn't you be shooting at cute little bunny rabbits or ducks instead?

Nick
02-27-2007, 04:49 PM
Thanks to both of you, it now works as expected. I've attached it as an example in case other people have a similar problem. Still got a lot more work to do on it :D