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\$
2
  • 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
    Commented Jul 9, 2018 at 11:22
  • \$\begingroup\$ transform.Rotate(0,0,180); use this to turn your car \$\endgroup\$ Commented Jul 9, 2018 at 11:46

1 Answer 1

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\$
2
  • 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
    Commented Jul 9, 2018 at 13:16
  • \$\begingroup\$ @DMGregory that's right thanks.I will update my answer \$\endgroup\$ Commented Jul 9, 2018 at 14:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .