0 votes

Hello,

I am implementing a simple spawner in 2D mode. My aim is to make them (each node) spawn with a 30-degree angle.

In Unity, I can solve this problem via Euler.

Vector2 v = Vector2.zero - base.transform.position;
v = Quaternion.Euler(0f, 0f, 30f) * v;

In Godot, how can I create a function that is exactly equivalent?

Currently, my implementation is:

var vector = target.position - position
var right = Quat(Vector3(vector.x, vector.y, 0), 30);
var left = Quat(Vector3(vector.x, vector.y, 0), -30);

if index == 1:
    vector.x = right.get_euler().x * vector.x;
    vector.y = right.get_euler().y * vector.y;
elif index == 2:
    vector.x = left.get_euler().x * vector.x;
    vector.y = left.get_euler().y * vector.y;

But it works wrong. The 'left' is throwing the back side and the angle of both 'left' and 'right' is not 30 degrees.

in Engine by (15 points)

2 Answers

+1 vote
Best answer

You can rotate a vector with a Transform2D.
Also note that angles in Godot are in radians.

var m = Transform2D().rotated(deg2rad(30));
# Clockwise rotation
var new_pos = m * vector;

# Counterclockwise 
new_pos = m.xform_inv(vector);

In-depth explanation about Transforms: https://docs.godotengine.org/en/3.1/tutorials/math/matrices_and_transforms.html

by (148 points)
selected by

Thank you it's working fine. :)

+1 vote
var q = Quat()
q.set_euler(Vector3(yaw,tilt,roll))
v = q * v

the angles must be in radians!!

by (282 points)

Well, how can i change the (x, y) at the same time with the given angle via Euler?

vector = get_rotated_vector(vector, 35)

Like this:

func get_rotated_vector(vector, degrees):
    var sinr = sin(degrees * PI/180);
    var cosr = cos(degrees * PI/180);

    vector.x = (cosr * vector.x) - (sinr * vector.y);
    vector.y = (sinr * vector.x) + (cosr * vector.y);

    return vector;

P.S: I get this code from StackOverflow, I couldn't find the source, sorry.

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