- Home /
How do I make an object move on the world space rather than the local space?
I'm trying to make an object move down a hallway every few seconds, but whenever it moves, I want it to be somewhere random between the walls. so I used a random. Range (-4, 4) to make the object move to somewhere between those two numbers. problem is, every time it moves, the range moves with it, so it can move outside the walls. How do I fix this?? This code does exactly what I want it to, except that it allows the object to move outside the walls of the hallway. void Start() { InvokeRepeating("Tp", 3, 3); } void Tp() { transform.Translate(new Vector3(Random.Range(-4, 4), 0f, 5f);
Answer by AaronBacon · Jun 03 at 12:13 AM
The problem is just that transform.Translate moves relative to the objects current position. if you set the transform position manually it'll always move to the same world coordinate eg:
transform.position = new Vector3(Random.Range(-4, 4), 0f, 5f);
However this will only work if the object starts at 0,0,0 in the world, which I'm assuming isn't what you want, so if you do this:
private Vector3 startPos;
void Start()
{
startPos = transform.position;
InvokeRepeating("Tp", 3, 3);
}
void Tp()
{
transform.position = startPos + new Vector3(Random.Range(-4, 4), 0f, 5f);
}
It will remember it's starting position and move randomly relative to that Starting Position
Okay, so I did this, but it doesn't seem to constantly move forward. I need it to get closer and closer to the player thats on the other end of the hallway. This code seems to make it move back and forth, but doesn't move it forward every time. How do I get it to move forward 5 units every time the InvokeRepeating goes off?
Set the integers in the the Random.Range()
function to something like 1 and 6... This should make it move anywhere between 1 and 5 units in-game every 3 seconds, Hope that helps :)
with this code that Aaron gave me, the object is staying in the hallway, but it's not moving down the hallway. it moves the 5 units once, then just zig-zags in place. so now I have to figure out how to make it move down the hallway with this code.
Your answer
![](https://koobas.hobune.stream/wayback/20220613061314im_/https://answers.unity.com/themes/thub/images/avi.jpg)