look_at.script 785 B

123456789101112131415161718192021222324
  1. function init(self)
  2. -- make sure the script will receive user input
  3. msg.post(".", "acquire_input_focus")
  4. end
  5. local function look_at(target_position)
  6. -- own positon
  7. local my_position = go.get_position()
  8. -- calculate the angle that this object has to rotate to look at the given point
  9. local angle = math.atan2(my_position.x - target_position.x, target_position.y - my_position.y)
  10. -- set rotation as a quaternion
  11. go.set_rotation(vmath.quat_rotation_z(angle))
  12. end
  13. function on_input(self, action_id, action)
  14. -- mouse/finger movement has action_id set to nil
  15. if not action_id then
  16. -- the position to look at (mouse/finger)
  17. local target_position = vmath.vector3(action.x, action.y, 0)
  18. -- rotate this object to look at the target position
  19. look_at(target_position)
  20. end
  21. end