- Home /
transform.right is using Global Space rather than local
I know similar questions have been asked/answered here before but none of the solutions are working. I'm spawning 'speed streaks' to give the impression of movement in my top-down space game. They spawn ahead of the player (relative to the player's movement) but no matter what method I use transform.Translate, transform.position, transform.localPosition etc, the 'streak' objects always move along global right/up etc. In the image below the X axis (red) is pointing against the direction the ship is actually moving (which is what I want), so I want the 'streaks' to move along that axis no matter which way it's pointing. Incidentally, as you can see the ship will not necessarily be pointing in the direction it is traveling as the player can strafe and rotate.
Just to clarify: the empty game object selected in the picture is a child of the ship.
Answer by _Prism_ · Aug 19, 2018 at 06:25 AM
OK, so I don't normally like answering my own posts, but it seems that transform.right/up etc only work correctly if they are not parented to anything.
Using a completely separate game object as the spawn point for the 'streaks' fixed the issue. However I also had to use transform.localRotation instead of Quaternion.identity, when instantiating the actual streak objects. For those interested: This code positions a leading object(ie, in front of a moving object's path):
void Update ()
{
tmpMagnitude = playerRb.velocity.magnitude;
tmpPos = transform.position;
tmpPos = new Vector3(player.position.x + (playerRb.velocity.normalized.x * (tmpMagnitude * 2.0f)), player.position.y + (playerRb.velocity.normalized.y * (tmpMagnitude * 2.0f)));
transform.position = tmpPos;
}
This code tracks the above object and points it the right way:
void Update ()
{
transform.right = ship.position - transform.position;
tmpPos = transform.position;
tmpPos = myTarget.position;
transform.position = tmpPos;
}
This code spawns the streak objects facing the right way:
IEnumerator SpawnStreaks()
{
while(streaking)
{
rndStreakSpawn = Random.Range(-1.0f, 1.0f);
Instantiate(streaks, transform.position, transform.localRotation);
print(transform.localPosition);
yield return new WaitForSeconds(1.0f);
}
}
A very specific problem/solution, but when you need it, you need it. ;)
Well, yes, if the object is a child of another object, then its rotation and position depends on parent's. So if you set child's position and rotation to (0, 0, 0) then it's 'transform.right' will be equal to 'transform.root.right' which is parent's right vector.
Interesting. That's not really clear in the documentation but it makes sense (ish).
Your answer
Follow this Question
Related Questions
C# Smoothing Out transform.Translate 4 Answers
stop object(door) translation 0 Answers
Help with casting a raycast C# 1 Answer
Distribute terrain in zones 3 Answers
Loop code just stops 2 Answers