Rotate to another object (SOLVED)

I want to rotate the spear to the chicken when it is moving. I use the code from the rotate example but does not work. I do not have the camera game object. How can I make it work?
current
This is my code

local to = go.get_position()
 local from = go.get_position("chicken")
 local angle = math.atan2(to.x - from.x, from.y - to.y)	
 rotation = vmath.quat_rotation_z(angle)
 print(angle)
 go.set_rotation(rotation)

Don’t change the order. It should be
to.y - from.y

3 Likes

What do you mean by “does not work”? Is it not rotating at all or is it not rotating to the correct angle?

@britzl It only rotates 90 degree

I also change to yours but it is same except it is on another side.

I update my code and it works well from 0 to 90 deg. But if the chicken move out of 90 deg, the spear stop rotating.

	local from = go.get_position("chicken")
	local direction = from - to
	local angle = math.atan2(direction.y, direction.x)
	local rotation = vmath.quat_rotation_z(angle)	
	
	go.set_rotation(rotation)
end

local from = go.get_position(hash("/arrow"))
local to = go.get_position(hash("/target"))
local direction = to-from
local angle = math.atan2(direction.y, direction.x)
local rotation = vmath.quat_rotation_z(angle)	
go.set_rotation(rotation, hash("/arrow"))
2 Likes

Make sure the two positions are in the same coordinate space. To be completely sure use go.get_world_position()

1 Like

Thank you @COCO. Your code works

@britzl I use @COCO code and it works. But I have to put the spear to a new game object that is sibling of hunter in the collection. The code I used before did not work because the spear was the child of the hunter. How do I change the code for the child object?

Oh. I found the solution for it. I just use go.get_world_position to get the child position. Thank you @britzl

1 Like