- Edited
Hello, so I have a 2d object which uses move_and_slide. How I can detect what object it has on its left for example when it collides? Should I always check the x and y position? Give me some best practices, please.
Hello, so I have a 2d object which uses move_and_slide. How I can detect what object it has on its left for example when it collides? Should I always check the x and y position? Give me some best practices, please.
With the function move_and_slide
, you can find out how many objects it has collided with via get_slide_count
, and the collisions themselves with get_slide_collision
. So having the logic for the collisions should best be put into a loop like this.
for i in get_slide_count():
var collision = get_slide_collision(i)
...
The contents of collision
are right here.
Thanks for the answer. Isn't better to check if count is greater than 0 before using for loop in order to save some cpu juice? Also should I compare x position of collided objects in order to know of its on node's left or right? I want to learn the good practices.
Also, what's the best way to know to what node a given node will collide before the collision occurs? For example I want to know what's ahead - lets say +5 pixels after the collision shape.
@edforx said: Also, what's the best way to know to what node a given node will collide before the collision occurs? For example I want to know what's ahead - lets say +5 pixels after the collision shape.
move_and_collide
(documentation. It's on both 2D and 3D KinematicBody nodes) would probably be ideal for this, especially if you set test_only
to true. I've done this before for collision detection and it has worked great.
I'm not sure if it is the best solution though. Using a short raycast is another viable solution.
@edforx said: Isn't better to check if count is greater than 0 before using for loop in order to save some cpu juice?
If the count is 0 then it wouldn't loop at all, and the if statement would be unnecessary, since you're testing a condition the first time through the loop anyway.