- Home /
Question by
GiulioPerosino · Feb 03, 2015 at 07:17 AM ·
raycastracing game
Limiting Raycast angle - Jump off ramps - Racing game
Hi, I'm relatively new to Unity, so be kind :P I'm making a game like Mario Kart and now I'm focusing on the player controller. In order to always keep the player parallel to the track I'm using raycasts, this is the code:
function HitTestWithRoad() {
var position:Vector3 = transform.position + transform.TransformDirection(Vector3.up) * 0.2;
var direction:Vector3 = transform.TransformDirection(Vector3.down);
var ray:Ray = new Ray(position, direction);
var hit:RaycastHit;
var distanceProva:float = 0.2;
Debug.DrawLine(ray.origin, ray.origin + ray.direction * distanceProva, Color.red);
var inGround:boolean = false;
if (Physics.Raycast(ray, hit, distanceProva)) {
if (hit.collider.tag == 'road'){
this.transform.position = hit.point;
//Debug.DrawLine(ray.origin, hit.point, Color.blue);
Debug.DrawLine(hit.point, hit.point + hit.normal, Color.green);
var curUpVector:Vector3 = position - hit.point;
var hitUpVector:Vector3 = hit.normal;
Debug.DrawLine(hit.point, hit.point + curUpVector.normalized, Color.white);
var targetQ:Quaternion;
var fPosition:Vector3 = transform.position + transform.TransformDirection(Vector3(0, 2.5, 1.0));
var fDirection:Vector3 = transform.TransformDirection(Vector3.down);
var fRay:Ray = new Ray(fPosition, fDirection);
var fHit:RaycastHit;
var fDistance:float = 5;
Debug.DrawLine(fRay.origin, fRay.origin + fRay.direction * fDistance, Color.cyan);
if (Physics.Raycast(fRay, fHit, fDistance)) {
if (fHit.collider.tag == 'road'){
Debug.DrawLine(fHit.point, fHit.point + fHit.normal * fDistance, Color.magenta);
targetQ.SetLookRotation(fHit.point - transform.position, hitUpVector);
}
}
if (targetQ == null) {
Debug.Log("None Forward");
targetQ.SetLookRotation(transform.TransformDirection(Vector3.forward), hitUpVector);
}
this.gameObject.transform.rotation = Quaternion.Slerp(this.gameObject.transform.rotation, targetQ, rotationT);
inGround = true;
}
}
return inGround;
}
My problem is when the player reaches a ramp. How can I prevent the raycast going to the side of the ramp like picture below? The result is when the player try to jump out is hooked to the side of the ramp.
Thanks for the attention, I hope I was clear.
raycast.jpg
(132.5 kB)
Comment