# Rotate to another object (SOLVED)

#1

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?

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)
``````
0 Likes

#2

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

3 Likes

#3

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

0 Likes

#4

@britzl It only rotates 90 degree

0 Likes

#5

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

0 Likes

#6

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
``````

0 Likes

#7
``````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"))``````
0 Likes

#8

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

0 Likes

#9

Thank you @cocosgames. Your code works

0 Likes

#10

@britzl I use @cocosgames 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?

0 Likes

#11

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

1 Like