I’m working on a side scroller controller.
What I have so far is enums that determine what direction you’re aiming based on what arrow keys are pressed (Forward and up, as well as down while in air) and one for the player state.
I have it set up so when the jump key is pressed and the player state is neither jumping or falling, you jump. The problem is, the behavior can’t detect collision with the level mesh yet, so you can only jump once and then you’re stuck in Falling forever instead of switching to Idle.
Can someone please help me understand how to use ray casting to detect ground collision?
It would also work for ceiling too because I need it to switch from jumping to falling when the ceiling is hit.
Here’s the code I have so far:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
#region Animations
public AnimationClip Idle;
public AnimationClip IdleLookingUp;
public AnimationClip Walk;
public AnimationClip WalkLookingUp;
public AnimationClip Jump;
public AnimationClip JumpLookingUp;
public AnimationClip JumpLookingDown;
public AnimationClip Fall;
public AnimationClip FallLookingUp;
public AnimationClip FallLookingDown;
#endregion
#region Variables
public float WalkSpeed;
public float Gravity;
public float JumpForce;
bool IsGrounded;
bool HasJumped;
bool HasHitCeiling;
Vector3 Forward;
CharacterController controller;
Object LevelMesh;
Object Player;
#endregion
#region Enums
enum PlayerDirection
{
Forward = 0,
Up = 1,
Down = 2
}
enum PlayerState
{
Idle = 0,
Walking = 1,
Jumping = 2,
Falling = 3,
Dead = 4
}
PlayerDirection playerDirection;
PlayerState playerState;
#endregion
// Use this for initialization
void Start () {
Forward = transform.forward;
LevelMesh = GameObject.FindGameObjectWithTag ("Level");
Player = gameObject;
}
// Update is called once per frame
void Update () {
print ("State: " + playerState + "; Direction: " + playerDirection);
//MOVE THE PLAYER IN FORWARD AT WALKSPEED
//JUMP
if (Input.GetButtonDown ("Jump") && playerState != PlayerState.Jumping && playerState != PlayerState.Falling)
{
rigidbody.AddForce (new Vector3(0, JumpForce, 0));
//print ("You are jumping.");
playerState = PlayerState.Jumping;
IsGrounded = false;
}
if (Input.GetButtonUp ("Jump") && playerState == PlayerState.Jumping)
{
playerState = PlayerState.Falling;
IsGrounded = false;
}
//FALL WHEN CEILING IS HIT
//ALSO BE ABLE TO LOOK UP WHILE GROUNDED
//AND LOOK UP & DOWN WHILE IN AIR
}
}