using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody rb;
bool Grounded, Sloped;
Vector3 moveDir, sideDir;
// Start is called before the first frame update
void Start()
{
moveDir = transform.forward;
rb = GetComponent<Rigidbody>();
}
private void isGrounded()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -transform.up, out hit ,4f))
{
Grounded = true;
}
else
{
Grounded = false;
}
}
private void isSloped()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -transform.up, out hit, 2f))
{
if (hit.transform.up != Vector3.up)
{
Sloped = true;
moveDir = slopeMoveDir(hit.transform.up);
sideDir = slopeSideDir(hit.transform.up);
} else
{
Sloped = false;
moveDir = transform.forward;
sideDir = transform.right;
}
}
}
private Vector3 slopeMoveDir(Vector3 a)
{
return Vector3.ProjectOnPlane(moveDir, a).normalized;
}
private Vector3 slopeSideDir(Vector3 a)
{
return Vector3.ProjectOnPlane(sideDir, a).normalized;
}
// Update is called once per frame
void Update()
{
isGrounded();
isSloped();
if (Input.GetKey(KeyCode.W))
{
rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, moveDir.z * 5);
}
if (Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, -moveDir.z * 5);
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector3(sideDir.x * 5, rb.velocity.y, rb.velocity.z);
}
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector3(-sideDir.x * 5, rb.velocity.y, rb.velocity.z);
}
}
}
I’m fairly new to programming and I wanted to get my feet wet with programming player movement using RigidBodies. I’ve been having fun so far, but I’m a little confused as to how I can get slope movements right.
I want to have a consistent speed on flat ground and moving up and down hill. I thought the ProjectOnPlane method would help me, but it still has troubles with going uphill and tends to skip going down. What math would I need to do to fix this?