- Home /
Ground Check In Unity3D 2019.4?
I'm making a game...
My player needs to jump and I can't seem to find a working 3D ground check using layer masks?
Any help would be appreciated!
Here is my code ( MovePlayer.cs ) :
using UnityEngine;
namespace MikaDev.PlayerMovement
{
public class MovePlayer : MonoBehaviour
{
[Header("Player Speed")]
[Tooltip("Modifies the player movespeed.")]
[Range(1f, 100f)]
public float moveSpeed;
[Header("Jump Force")]
[Tooltip("Modifies the jump force.")]
[Range(1f, 10000f)]
public float jumpForce;
// Rigidbody
Rigidbody rb;
// The LoGiC
Vector3 change;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float Horizontal = Input.GetAxisRaw("Horizontal");
float Vertical = Input.GetAxisRaw("Vertical");
change = Vector3.zero;
change.x = Horizontal;
change.z = Vertical;
if (Input.GetButtonDown("Jump"))
{
Jump();
}
// Player moving
if (change != null)
{
Move();
}
}
void Move()
{
rb.AddForce(change * Time.deltaTime * moveSpeed, ForceMode.Impulse);
}
void Jump()
{
rb.velocity = Vector3.up * jumpForce * Time.deltaTime;
}
}
}
Comment
Answer by MKGPlayz · Jul 25, 2020 at 02:57 PM
Fixed the issue :P
I used OnCollisionStay to do a little bit of math.
Here is the code:
using UnityEngine;
namespace MikaDev.PlayerMovement
{
public class MovePlayer : MonoBehaviour
{
[Header("Player Speed")]
[Tooltip("Modifies the player movespeed.")]
[Range(1f, 100f)]
public float moveSpeed;
[Header("Jump Force")]
[Tooltip("Modifies the jump force.")]
[Range(1f, 10000f)]
public float jumpForce;
public bool isGrounded;
// Rigidbody
Rigidbody rb;
// The LoGiC
Vector3 change;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float Horizontal = Input.GetAxisRaw("Horizontal");
float Vertical = Input.GetAxisRaw("Vertical");
change = Vector3.zero;
change.x = Horizontal;
change.z = Vertical;
if (Input.GetButtonDown("Jump"))
{
Jump();
}
// Player moving
if (change != null)
{
Move();
}
}
void Move()
{
rb.AddForce(change * Time.deltaTime * moveSpeed, ForceMode.Impulse);
}
void Jump()
{
rb.velocity = Vector3.up * jumpForce * Time.deltaTime;
}
private void OnCollisionStay(Collision collision)
{
if (collision.contacts[0].normal.y > 0.8)
isGrounded = true;
}
private void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
}
}