1
\$\begingroup\$

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?

\$\endgroup\$
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – DMGregory Jul 9 '18 at 11:22
  • \$\begingroup\$ transform.Rotate(0,0,180); use this to turn your car \$\endgroup\$ – Seyed Morteza Kamali Jul 9 '18 at 11:46
1
\$\begingroup\$

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

enter image description here

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);

}
}

enter image description here

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();
}
}
\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Jul 9 '18 at 13:16
  • \$\begingroup\$ @DMGregory that's right thanks.I will update my answer \$\endgroup\$ – Seyed Morteza Kamali Jul 9 '18 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.