Hello,
I am a beginner game developer, recently trying to get into code.
I am working on a 3d platformer that is supposed to be kinda similar to crash bandicoot, but the player is riding a skateboard. While I’ve been trying to keep it basic, I keep running into problems I don’t know how to solve.
currently I am trying to use a Rigid Body controller, this is the closest I got to what I want:
{
public float maxSpeed = 10f;
public float acceleration = 5f; //rate of acceleration
public float drag = 3f;
public float turnSpeed = 120f;
public float jumpForce = 5f;
public float brakeSpeed = 15f;
private float currentSpeed = 0f;
private float moveInput;
private float turnInput;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.constraints = RigidbodyConstraints.FreezeRotationZ;
}
void Update()
{
GetDirectionalInput();
Jump();
HandleBraking();
}
void FixedUpdate()
{
MovePlayer();
}
void MovePlayer()
{
//calc acceleration
if(moveInput > 0)
{
currentSpeed += acceleration * Time.deltaTime;
}
else if( moveInput <0)
{
currentSpeed -= acceleration * Time.deltaTime;
}
//apply drag when no input
if(moveInput == 0)
{
currentSpeed -= drag * Time.deltaTime;
}
// clamp speed between 0 and max speed
currentSpeed = Mathf.Clamp(currentSpeed, 0, maxSpeed);
//calc movedirection based on input
Vector3 moveDirection = transform.forward * currentSpeed;
rb.velocity = new Vector3(moveDirection.x, rb.velocity.y, moveDirection.z);
if(turnInput != 0)
{
Quaternion turnRotation = Quaternion.Euler(0, turnInput * turnSpeed * Time.deltaTime, 0);
rb.MoveRotation(rb.rotation * turnRotation);
}
}
void GetDirectionalInput()
{
moveInput = Input.GetAxis("Vertical");
turnInput = Input.GetAxis("Horizontal");
}
void HandleBraking()
{
if(Input.GetKey(KeyCode.Space))
{
currentSpeed -= brakeSpeed * Time.deltaTime;
}
//prevent backwards speed
currentSpeed = Mathf.Max(currentSpeed,0);
}
void Jump()
{
if(Input.GetKeyDown(KeyCode.J))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
basically, I can’t get the board to not rotate around the Z axis, unless the x axis is constrained too.
another problem is collisions in general. I don’t have complicated ramps in my game but even so, just any slope is enough for the rigid body to act kinda weird.
I thought about trying to do something with Character Controller, but that was also kinda awkward with slopes, and needed a lot more code to add proper physics. I also thought about using wheel colliders or something similar with raycasts for each wheel. but that might be over complicating it…
I would have added a video but I can’t because I am a new user apparently…
anyway, if anyone has any tips to improve this code, or any different approaches I would love some help.
thanks in advance!