Home > front end >  Find RayCast Vector and move away from it in Godot
Find RayCast Vector and move away from it in Godot

Time:02-03

I am making a game in Godot and I want one of my enemies to move away from the ground when it detects a collision with RayCasts. I set up my RayCasts like this: enter image description here I tried using this code:

for i in dodge.get_children():
    if i.is_colliding():
        var velocity = Vector2().rotated(deg2rad(i.rotation_degrees))
        move_and_collide(velocity * -charge_speed * delta)

Where dodge holds all the RayCasts and I go through all its children and check for collisions. I then tried rotating the Vector2 by the rotation of the RayCasts, since that is how I rotated them instead of using Cast To, and tried moving it by that Vector, but it didn't work. It didn't even move in the wrong direction. It didn't move at all.

How would I go about solving this?

CodePudding user response:

Look at this line:

var velocity = Vector2().rotated(deg2rad(i.rotation_degrees))

Here you create a new Vector with Vector2(). Which is equivalent to Vector2(0.0, 0.0).

When you rotate Vector2(0.0, 0.0), regardless of the angle, it will remain Vector2(0.0, 0.0).

As a result velocity will be Vector2(0.0, 0.0).

Then in this line you scale velocity:

move_and_collide(velocity * -charge_speed * delta)

If you multiply zero, I mean Vector2(0.0, 0.0), by any number it is still Vector2(0.0, 0.0).

And so it will move according to Vector2(0.0, 0.0), i.e. not at all.


So you need to change that starting Vector2(). It could be Vector.RIGHT or Vector.UP, or more likely Vector.DOWN. How do you know? Well, it is the direction of the RayCast2D if you don't rotate them.


Or, alternatively, you could use cast_to also. I believe it is like this:

var velocity = i.global_transform.basis_xform(i.cast_to).normalized()

Using basis_xform should apply the rotation (and any skewing), but not the translation. I also added normalized because I don't know if the result will be an unit vector, so it is to make sure it is.

  • Related