I have troubles with checking for ground in my 2.5D platformer. Here’s script I use for player’s movement
using UnityEngine;
using System.Collections;
public class playerMovement : MonoBehaviour {
public float movementForce = 0.1f;
public float jumpForce = 1f;
public bool ground = false;
// Update is called once per frame
void Update () {
//defining ray
Ray bottom = new Ray(this.transform.position,Vector3.down);
//defining RaycastHit
RaycastHit hit = new RaycastHit();
//testing for collision, should work, but it doesn't, even if ray is halfway through object
//this returns false no matter what I try
bool hitground = this.collider.Raycast(bottom,out hit,20);
if (hitground){
//if it collided, test if it is in right distance
ground = hit.distance<=0.6;}
//drawing ray
Debug.DrawRay(bottom.origin,bottom.direction);
//logging distance and if it hit (always gives Hit distance: 0 Did hit: false)
Debug.Log("Hit distance: "+hit.distance.ToString()+" Did hit: "+hitground.ToString());
//movement, this works fine
if (Input.GetAxisRaw("Horizontal")==-1){this.rigidbody.AddForce(-movementForce,0,0);}
if (Input.GetAxisRaw("Horizontal")==1){this.rigidbody.AddForce(movementForce,0,0);}
//jumping, this doesn't due to stupid raycasting bug.
if ((ground)&&(Input.GetButtonDown("Jump"))){this.rigidbody.AddForce(0,jumpForce,0);}
}
}
Another thing is that I’m using rigid body for movement and spherical collision shape (player character is and will be cube as this is minimalistic game), so player can climb on smaller platforms.
Theoretically it should work as ray is shown passing directly through platform (another cuboid, I’m talking about ray drawn by Debug.DrawRay), but it doesn’t.