- Home /
rotate object until rigitbody.velocity is facing the target
Hi, I need a bit of help, i think its a simple problem but i cannot figure it out. Basically what i want to do is rotate object left or right so that the direction of rigidbody.velocity vector is pointing at target object. Or at least how do i find if target object is to the left or right from the direction of my rigidbody.velocity vector. Please note that my transform.forward is not the same as rigitbody.velocity
Any ideas how i can code that?
Thanks in advance
So that the direction of rigidbody.velocity vector is pointing at target.
So you want the rigidbody to move towards the target?
Answer by carle13 · Jul 14, 2017 at 06:25 PM
Well, if I understood your question what it seems that you want to do is similar to something I've done for a game.
In my game there are police cars that chase the player, so to make them point to the player's car I check if according to the police's local coordinates the player's car is at x positive which is right or x negative which is left. I do this with two simple lines of code I found in this tutorial https://www.youtube.com/playlist?list=PL67XFC3MYQ6JV0l9485jB1Dpn4atLsFSo The lines are:
Vector3 steerVector = transform.InverseTransformPoint(nav.steeringTarget);
steering = maxSteer * (steerVector.x / steerVector.magnitude);
So in the first line it gets the position of the target relative to the police's local system of coordinates. In the second I divide the x component of that vector by it's magnitude, in that way I can know how much of x that vector has. In the image above these are the values I get So as in the code I'm dividing the x component (8.71) by the magnitude (23.57) I get a turn of 0.37 (the division only gives values between 0 and 1). Then I multiply that amount by my maxSteer which is an angle of how tight I want the turns to be.
As another example, if I put the player's car in front of the police car I get the x component (-0.26) and the magnitude (64) which gives me a turn of -0.004 which is almost 0 because it doesn't need to turn as the player is already in front.
And if the local coordinates of your object are different you can just try changing the x component by the y or z component. I may have got wrong the values but I hope you get the idea.
Thanks for your reply. Unfortunately your solution is incorrect for my problem. It would work perfectly if i was trying to have transform.forwards direction of a vector to face target. But i am trying to have direction of rigidbody.velocity vector to face target.
Red arrow is transform.forfwards Vector Black arrow is rigidbody.velocity vector
i need to rotate car till black arrow points at target.
So you want to rotate the object to change the direction of it's movement with it, kind of like the object had a propeller on it's back and when you rotate the object the direction that the propeller is pushing the object changes?