# How to rotate an object to a specific transform?

I am working on a car racing game and there are some times when the car rotates and ends up on its roof. On those situations I want the car to respawn on the same location. What can I do to rotate it so the car ends up on its wheels?

• Presumably you've tried setting the object's transform.rotation or Rigidbody rotation, yes? What did you try, and how did the results differ from what you want? Commented Jul 9, 2018 at 11:22
• transform.Rotate(0,0,180); use this to turn your car Commented Jul 9, 2018 at 11:46

you can check if roof hit with ground then respawn it.

attach this code to your car's roof:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RoofCheck : MonoBehaviour {

//if roof hit with ground
void OnCollisionStay(Collision other)
{
if(other.gameObject.tag == "Ground"){
Respawn();
}
}

void Respawn(){
//Reset to same position
var respawnPos = transform.position;
respawnPos.y += 5;
transform.position = respawnPos;

//Reset rotation
transform.rotation = Quaternion.LookRotation(transform.forward);

}
}


use the direction to the next waypoint on the track:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class RoofCheck : MonoBehaviour {
public List<Transform> wayPoint = new List<Transform>();

//if roof hit with ground
void OnCollisionStay(Collision other)
{
if(other.gameObject.tag == "Ground"){
Respawn();
}
}

void Respawn(){
//Reset to same position
var respawnPos = transform.position;
respawnPos.y += 5;
transform.position = respawnPos;

Vector3 closestPoint = FindClosestTarget(wayPoint).position;
transform.rotation = Quaternion.LookRotation(new Vector3(0,0,-closestPoint.z));

}

Transform FindClosestTarget(List<Transform> list)
{
Vector3 position = transform.position;
return wayPoint.OrderBy(o => (o.transform.position - position).sqrMagnitude).FirstOrDefault();
}
}

• You might want to replace Quaternion.identity with Quaternion.LookRotation(transform.forward) (or use the direction to the next waypoint on the track) so the player is facing in a relevant direction on respawn rather than always facing north. Commented Jul 9, 2018 at 13:16
• @DMGregory that's right thanks.I will update my answer Commented Jul 9, 2018 at 14:20