- Home /
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.
Answer by mjdb3d · Oct 19, 2018 at 05:07 PM
link textTry 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);
}
Answer by Glurth · Oct 19, 2018 at 05:05 PM
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);
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.
Your answer
Follow this Question
Related Questions
transform.Translate but Transform has Rotation!=0 1 Answer
Rotation to go from one direction to another? 0 Answers
Rotation of character resets when joystick is released 3 Answers
why my wander script makes my enemies move badly? 1 Answer
Checking vector3 gameObject is about to move to (pathfinding collision detection) 1 Answer