Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vector3 "rotate towards another Vector3" function #21383

Closed
ghost opened this issue Aug 24, 2018 · 4 comments
Closed

Vector3 "rotate towards another Vector3" function #21383

ghost opened this issue Aug 24, 2018 · 4 comments
Labels

Comments

@ghost
Copy link

ghost commented Aug 24, 2018

It would be nice to have a Vector3 function that rotates it towards another Vector3, restricted to a maximum rotation delta. This exists in Unity, and it's very handy since it's kind of hard to do on your own. Especially when you don't know what you're doing... like me.

@swarnimarun
Copy link
Contributor

Read this, we have a look at the function for the most basic 3D node Spatial.
http://docs.godotengine.org/en/3.0/classes/class_spatial.html#class-spatial-look-at

@ghost
Copy link
Author

ghost commented Aug 24, 2018

@swarnimarun I'm aware of that, but that isn't quite what this is asking for. look_at is for aligning a transform toward a point in space, but what I'm asking for here is just an easy way to rotate a vector toward (or away from) another, along a plane that consists of the two vectors. In practice, this would be a way to bypass the need to learn about the cross product.

@BastiaanOlij
Copy link
Contributor

From the top of my head (there might be typos in here):

# normalise both vectors:
var va_n = va.normalized()
var vb_n = vb.normalized()

# take the cross product and dot product
var cross = va_n.cross(vb_n).normalized()
var dot = va_n.dot(vb_n)

# acos(dot) gives you the angle (in radians) between the two vectors which you'll want to clamp to your maximum rotation (convert it to radians)
var angle = clamp(acos(dot), -max, max)

# and now you can rotate your original 
var result = va.rotated(cross, angle)

@ghost
Copy link
Author

ghost commented Aug 25, 2018

@KellyThomas Oh wow, I didn't even know Vector3.slerp() existed... I'm pretty stupid!

To calculate t based on a max rotation delta, I think I can just do this: clamp(inverse_lerp(0, v1.angle_to(v2), max_delta), -1, 1).

I think I can create a function in a utility singleton that does this... or, I can just use @BastiaanOlij's code that he posted as I was writing this!!! Either way, this probably isn't needed anymore.

@ghost ghost closed this as completed Aug 25, 2018
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants