+2 votes

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()?

in Engine by (28 points)
edited by

1 Answer

+3 votes

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
by (22,069 points)

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.

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.

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());

    }
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.