0 votes

What I mean by this is the rotationdegrees of the sprite will snap to 0, 90, 180, 270 depending on what value I want to set it to. The goal is to have an enemy lookat(player.position) and yet it stays rotated at 90 degree intervals.

in Engine by (19 points)

1 Answer

+1 vote

This might not be the most efficient way, but it should work:

#These are your snap vectors
var up = Vector2(0,-1)
var down = Vector2(0,1)
var left = Vector2(-1,0)
var right = Vector2(1,0)

#This will give you the vector to the player
var look_vector = player.position - enemy.position

#The take the dot product of this vector to each of the snap vectors.
#The one with the biggest dot product is the "most parallel".

var snap_vector = up
var max_dot_product = look_vector.dot(up)

var dot_product = look_vector.dot(down)
if dot_product > max_dot_product:
   max_dot_product = dot_product
   snap_vector = down

dot_product = look_vector.dot(right)
if dot_product > max_dot_product:
   max_dot_product = dot_product
   snap_vector = right

dot_product = look_vector.dot(left)
if dot_product > max_dot_product:
   max_dot_product = dot_product
   snap_vector = left

#You will end up with the closest snap_vector at the end
by (35 points)

Thanks! It worked perfectly!

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.