Hello everyone
I have recently come into a little problem when I decided to code in some movement. Whenever I try to jump (which uses Rigidbody.velocity) it will stop all of the movement which I use to move from side to side (uses Rigidbody.AddForce). Here is the code: (I’m using 2D by the way)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public Rigidbody2D rb;
public GameObject Player;
public float RunSpeed = 10f;
public BoxCollider2D hitbox;
[SerializeField] LayerMask platformsLayerMask;
public KeyCode A = KeyCode.A;
public KeyCode D = KeyCode.D;
public KeyCode W = KeyCode.W;
void Start()
{
Player = GameObject.Find("Player");
rb = Player.GetComponent<Rigidbody2D>();
hitbox = Player.GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
if (IsGrounded() && Input.GetKeyDown(W))
{
float JumpForce = 12.5f;
rb.velocity = Vector2.up * JumpForce;
}
if (Input.GetKey(A))
{
ForceChange(rb, Vector3.right * -RunSpeed, 2f);
}
if (Input.GetKey(D))
{
ForceChange(rb, Vector3.right * RunSpeed, 2f);
}
}
public bool IsGrounded()
{
RaycastHit2D jumpDetect = Physics2D.BoxCast(hitbox.bounds.center, hitbox.bounds.size, 0f, Vector2.down, .01f, platformsLayerMask);
return jumpDetect.collider != null;
}
public static void ForceChange(Rigidbody2D rb, Vector3 velocity, float force = 1f, ForceMode2D mode = ForceMode2D.Force)
{
if(force == 0 || velocity.magnitude == 0)
{
return;
}
velocity = velocity + velocity.normalized * 0.2f * rb.drag;
force = Mathf.Clamp(force, -rb.mass / Time.fixedDeltaTime, rb.mass / Time.fixedDeltaTime);
if(rb.velocity.magnitude == 0)
{
rb.AddForce(velocity * force, mode);
}
else
{
var velocityProjected = (velocity.normalized * Vector3.Dot(velocity, rb.velocity) / velocity.magnitude);
rb.AddForce((velocity - velocityProjected) * force, mode);
}
}
}
I want to know if there is some way to fix this, and I feel that changing the rb.AddForce to rb.velocity won’t do the trick for me, because I want the speed to slowly rise before it reaches the maximum speed. Thanks in advance!