# Rotate prefab to face movement directio

I need help with prefab rotation

I have script attached to gameobject that spawns prefabs just as intended.
void Update()
{

``````        if (Time.time > nextSpawn)
{
Spawn();
}
}

public void Spawn()
{
nextSpawn = Time.time + spawnRate;
randSpawnX = Random.Range(leftBorder, rightBorder);
whereToSpawn = new Vector2(randSpawnX, transform.position.y);
SpawnRandomBug();
}

public void SpawnRandomBug()
{
randomInteger = Random.Range(0, bugs.Length);
Instantiate(bugs[randomInteger], whereToSpawn, Quaternion.identity);
}
}
``````

I also have script atached to prefabs that move that as i like

private void Start()
{
randX = Random.Range(-2.7f, 2.7f);
randY = Random.Range(-4.9f, 4.9f);
moveVector = new Vector3(randX, randY, 0f);
}

``````    void Update () {
MoveTheBug();
}

public void MoveTheBug()
{
transform.Translate(moveVector * moveSpeed * Time.deltaTime);
}
``````

But I just can’t make prefabs face direction of movement. I tried several things found on this forum but I just can’t make it work.

transform.Translate(moveVector * moveSpeed * Time.deltaTime);

`````` //I assume moveVector is a local-space vector
Vector3 worldMoveDir = transform.TransformDirection(moveVector.normalized);
transform.LookAt(worldMoveDir);
``````

Edit: ah, for 2d on the XY plane, you would need to add, the up parameter.

``````transform.LookAt(worldMoveDir, new Vector3(0,0,1) );
``````

It doesn’t translate: oops, my mistake- once pointing in the right “world-space” direction- your translate function, which takes a local-space vector, should always be “forward”.

``````transform.Translate(new Vector3(1,0,0) * moveSpeed * Time.deltaTime);
``````

[126376-rotateprefabtofacemovementdirection.zip|126376]Try this

``````     void Update () {
MoveTheBug();
}

public void MoveTheBug()
{
transform.Translate(Vector3.up * moveSpeed * Time.deltaTime);

float angle = Quaternion.FromToRotation(Vector3.up, moveVector).eulerAngles.z;

transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
``````

Unfortunately, neither of those worked.

@Glurth - your version creates spinning of prefabs around y axis and they do translate to target direction any more. Rays show direction where they should translate.

@mjdb3d - you version creates similar situation with little more rotation.