Home > Software engineering >  Unity 2D Transfrom.position not working for moving my object. the most it moves is 0.4 units
Unity 2D Transfrom.position not working for moving my object. the most it moves is 0.4 units

Time:10-01

hello so I have been making a small game with unity 2D. and I am making a little enemy that moves randomly by picking a random set rotation and moving in that direction. I have tried a few things and maybe what I'm doing wrong is stupid and I'm just not seeing it. here is all the methods of what I have tried:

// just as a test too see if it would actually work
// in the start method I put:
flaot RandomXmin = Random.Range(1, 2) 
transform.position = new Vector3(RandomXmin, 0) * Time.deltaTime;
// even if you take out the RandomXmin and replace it with a number i still got the same result
// the farthest it got was o.4 or some really low odd number.

then I tried

// i put this in the start method as well. still nothing.
transform.Translate(Vector3.up * 2 * Time.deltaTime);

I'm not exactly sure what to try now or what to do. so if anyone has any insight hen I would greatly appreciate it.

CodePudding user response:

As mentioned in the comments, the reason you are observing a small translation is that you multiply by time of last frame (at 60fps this is equivalent to ~0.016.

Just multiplying by Time.deltaTime does not make the parameter animate. There's various ways to make the value transition from one to another, you can start a Coroutine, you could animate it in Update when a flag is up, or when target value is different from current, or use a plugin like LeanTween / DoTween etc.

CodePudding user response:

First of all you are doing stuff in Start which is called exactly ONCE.

You rather want to put it into Update which is called repeatedly every frame.


and then your first attempt

flaot RandomXmin = Random.Range(1, 2) 
transform.position = new Vector3(RandomXmin, 0) * Time.deltaTime;

will hard set your object to a position with RandomXmin * Time.deltaTime, 0, 0. Where RandomXmin is some float value between 1 and 2 and Time.deltaTime basically the time passed since the last frame. Within Start this an have invalid values anyway but would usually be really small. (e.g. 60 fps => 1/60 = 0.001666..)

And the second one

transform.Translate(Vector3.up * 2 * Time.deltaTime);

is already more suitable for moving your object with a constant velocity of 2 units per second upwards .. however still you call it only once.


So it is up to you but you would probably do something like e.g.

private void Update()
{
    transform.Translate(Vector3.up * 2 * Time.deltaTime);
    // basically equals
    //transform.localPosition  = Vector3.up * 2 * Time.deltaTime;
}
  • Related