- Home /
Calculate Vector3 position using and Object position + rotation and an angle
The title sounds a little moronish, most likely the question will sound the same way. Sorry for that in advance.
Top down 2d view game. I have an Parent object named Ship, and a child object named Motor (at the back of the ship). I also have some child objects named Steer (with a number) and depending on which Steer is active right now, i apply force to the Motor position. Whole thing is moving with Rigidbody2D.AddForceAtPosition. This way i can move forward or backward and rotate Ship at the same time.
Code looks like this:
Vector3 Steer = Steer0.transform.position;
Vector3 forceDirection = (Motor.transform.position - Steer).normalized;
shipBody.AddForceAtPosition(forceDirection * enginePower, Motor.transform.position);
The problem is, i have to use static Steer objects to get their Vector3 coordinates.
I would like to just calculate where is a Steer suppose to be, without having any real object at that position.
I have a Motor position and Motor rotation, i know the angle Between Motor and Steer (at the second picture). I also know the distance between Motor position and a steer position (lets say it 1, since it does not matter), but i can't understand how do i get Vector3 Steer position from this? I've tried to use something like this:
Vector3 CalculateSteerCoordinates(float degrees)
{
var radians = degrees * Mathf.Deg2Rad;
var x = Motor.transform.position.x + Mathf.Cos(radians);
var y = Motor.transform.position.y + Mathf.Sin(radians);
Vector3 pos = new Vector3(x, y, 0);
return pos;
}
It works, but it does not consider Motor rotation, only it's coordinates. As a result, it will give incorrect position as soon as i rotate the ship.
Answer by Namey5 · Oct 19, 2020 at 11:31 AM
You can use what you already have, just transform those coordinates from the motor's local space to world space;
Vector3 CalculateSteerCoordinates(float degrees, float distance)
{
float radians = degrees * Mathf.Deg2Rad;
Vector3 localPos = new Vector3 (Mathf.Cos (radians), Mathf.Sin (radians), 0) * distance;
return Motor.transform.TransformPoint (localPos);
}
Thank you for the answer. Just tested it very quick (with a drawn objects) and it seems to be working great. Was trying the same thing today but i was adding $$anonymous$$otor.transfrom.position, which was messing everything up.
Thanks a lot
Your answer
Follow this Question
Related Questions
Vertical & horizontal movement world axis (top view) 1 Answer
how to stop the camera to follow the player on his jump movement ? 2 Answers
2D Topdown Character Contoller 0 Answers
Smooth Camera/Object Movement 1 Answer
In the breakout tutorial,why does the paddle movement use Update() instead of FixedUpdate()? 1 Answer