Using test_move()?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By KinguKurimuzon

I have a KinematicBody2D circling around a Path2D, and I need a way to check if anything is directly in front of itself. TestMove() seems like it’d be able to that, but I don’t quite understand how it works and I can’t find any good tutorials for using it. Can anyone explain in detail how to use TestMove()?

:bust_in_silhouette: Reply From: kidscancode

You’re not going to find a tutorial for every single function of every node. The description of test_move() in the docs seems pretty good:
http://docs.godotengine.org/en/latest/classes/class_kinematicbody2d.html#class-kinematicbody2d-test-move

You need a starting point (the body’s current transform) and a relative movement vector. The result is true if something would have hit.

I don’t know much about your setup, but for example:

if test_move(transform, velocity * delta):
    speed = 0
else:
    speed = 100

Is there something in particular you don’t understand about that?

Alternatively, you might use a Raycast2D projecting ahead of the body to solve this problem.

if $RayCast2D.is_colliding():
    speed = 0
else:
    speed = 100

Thanks, I’m not too good with Vector math and I didn’t realize it’s supposed to use the motion vector. I was considering using a Raycast earlier, but I was worried about it being imprecise. I’ll try it out to see if it works better, though.

KinguKurimuzon | 2018-04-26 06:27

This might help you with the vector math.

Kinematic body isn’t necessarily bad (again, I don’t know the details). I’m using that setup - kinematic body moving along a Path2D in my Topdown Tank Battle tutorial. I’m opting for the raycast method, although I haven’t posted the code for that part yet.

kidscancode | 2018-04-26 06:36

One last question about TestMove(), I’ve got my NPC checking for collisions with it now, but it doesn’t seem to recognize collisions above it or to the left of it. I assume this has to do with negative values, but do you have any idea what’s going on here? Here’s the code for my physics process. follow is a PathFollow2D.

Vector2 motion = new Vector2();

    float OldOffset = follow.GetOffset();
    float StandardMovement = motionSpeed * delta;

    follow.SetOffset(follow.GetOffset() + (motionSpeed * delta));
    
    motion += follow.Position;
    motion -= Position;
    MoveAndCollide(motion);

    if (TestMove(Transform, motion))
    {
        follow.SetOffset(OldOffset);
        SetPosition(follow.GetPosition());
        
    }

KinguKurimuzon | 2018-04-26 07:30