Question by
danterodriguez435 · Dec 09, 2020 at 08:22 PM ·
c#physicsprogrammingslopes
I need help with Sonic style slope physics
So, I have 1 year of experience in unity and I'm programming a Sonic fan game, and I have problems with 360 degrees slope physics, and jumping higher depending on movement speed and the current slope angle. This is my code of slope physics:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
private Transform cam;
public float maxSpeed = 20f;
public float acceleration = 4f;
public float deceleration = 6f;
public float minLoopRunningSpeed = 7f;
private float forwardVelocity;
public float jumpForce = 6f;
public float jumpDelay = 0.4f;
private float jumpTimer;
private bool isGrounded;
private void Awake()
{
rb = GetComponent<Rigidbody>();
cam = Camera.main.transform;
}
private void Update()
{
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
input.Normalize();
jumpButtonPress = Input.GetButtonDown("Jump");
jumpButtonHold = Input.GetButton("Jump");
if(input.sqrMagnitude > 0f)
{
forwardVelocity += input.sqrMagnitude * acceleration * Time.deltaTime;
forwardVelocity = Mathf.Clamp(forwardVelocity, -maxSpeed, maxSpeed);
float targetAngle = Mathf.Atan2(input.x, input.y) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.LerpAngle(transform.eulerAngles.y, targetAngle, 15f * Time.deltaTime);
transform.rotation = Quaternion.Euler(transform.eulerAngles.x, angle, transform.eulerAngles.z);
}
}
private void FixedUpdate()
{
rb.velocity = transform.forward * forwardVelocity + Vector3.up * rb.velocity.y;
RaycastHit hit;
if(Physics.Raycast(transform.position, -transform.up, out hit, 1.5f))
{
isGrounded = true;
transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
rb.useGravity = forwardVelocity >= minLoopRunningSpeed;
}
else
{
isGrounded = false;
transform.rotation = Quaternion.Euler(0f, transform.eulerAngles.y, 0f);
rb.useGravity = jumpTimer <= 0f;
}
if(jumpButtonPress && isGrounded)
{
rb.AddRelativeForce(Vector3.up * jumpForce, ForceMode.Impulse);
jumpTimer = jumpDelay;
}
if(jumpTimer > 0f)
{
if(jumpButtonHold)
jumpTimer -= Time.deltaTime;
else
jumpTimer = 0f;
}
}
}
I have some bugs like when I go on a slope I fly away and I need a code to jump higher depending on forwardVelocity and the hit normal. Can someone help me???
Comment
Your answer
Follow this Question
Related Questions
Making a game object follow the player C# 1 Answer
What is the correct way to learn unity scripting ? 2 Answers
Swipe Power Limit in a ball 0 Answers
How to pick up an object in hand e.g. a bat C# 0 Answers
C# code understanding problem 2 Answers