0 votes

I want to rotate a KinematicCharacter3D towards another one, rotating only one axis. I know I can use rotate_y() for what I want, but I don't understand how to calculate the direction and angle so that it will rotate towards another enemy.

I tried the look_at() function but it is buggy for what I want at least in my project. Anyone?

asked Jun 21 in Projects by Zero (77 points)
edited Jun 21 by Zero

1 Answer

+1 vote
Best answer

You'll need a little math for that.

so first you'll get the difference of the 2d vectors of the objects (x and y for example)

then, you need to get the arc tangent of the value you got previously

it would look something like this:

var a = Vector2(200, 600)
var b = Vector2(300, 100)
func getangle():
   var diff = Vector2(a.x - b.x,a.y - b.y) #or can just be a - b but can be bothered to check
   return atan(diff.y,diff.x) #return angle in radians. use radtodeg() if you want the angle in degrees.

the vectors used will be the axis that isnt the axis of rotation. example:
getting y rotation using x and z vectors from both objects.

after that, set the bodies rotation.someaxis to getangle!

answered Jun 21 by dustin (406 points)
selected Jun 22 by Zero

So in this case I need to get the globaltransform.origin.x and globaltransform.origin.z of the nodes I want, is this it? With a being the target node position and b being the node position itself?

I had to use atan2 cause atan only asked for 1 argument, but it doesn't rotate right still.

Code:

var a = Vector2(locked_on_enemy.get_global_transform().origin.x, locked_on_enemy.get_global_transform().origin.z)
var b = Vector2(global_transform.origin.x, global_transform.origin.z)

rotation.y = getangle(a, b) 

func getangle(a: Vector2, b: Vector2):
        var diff = Vector2(a.x - b.x,a.y - b.y) #or can just be a - b but can be bothered to check
        return atan2(diff.y,diff.x) #return angle in radians. use radtodeg() if you want the angle in degrees.

yeah! that should work. be sure to actually set the rotation of the object.

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 How to use this Q&A? before posting your first questions.