Question by
Alcatrazuelo · Mar 21 at 12:34 AM ·
2d gamemovement scriptforceplayer movementdash
[2D] How to stop 2 vectors from adding force on each other
Hello everyone, this is my first time working with code and Unity, so to get familiarized with the workflow I'm recreating mechanics from retro games, starting with Alucard's moveset from Symphony of the Night. The problem is with his backdash adding up with the force of the walk, if I'm pressing right and backdash, then it does the backdash, but slower and if I'm pressing left and backdash it goes faster. Here's my code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Walking")]
public float WalkSpeed = 10f;
public float JumpForce = 12f;
public float GroundDetectionRadius = 0.25f;
[Header("BackDash")]
public float DashForce = 10f;
public float DashDuration = 1;
public float DashCD = 1;
[SerializeField] private LayerMask JumpableGround;
private Rigidbody2D rbody;
private SpriteRenderer sprender;
private BoxCollider2D bcoll;
float Xinput;
bool IsGrounded;
bool jump;
bool isDashing;
bool CanDash = true;
IEnumerator DashCor;
private void Start()
{
rbody.gravityScale = 3;
}
private void Awake()
{
rbody= GetComponent<Rigidbody2D>();
sprender= GetComponent<SpriteRenderer>();
bcoll= GetComponent<BoxCollider2D>();
}
private void Update()
{
IsGrounded= Physics2D.BoxCast(bcoll.bounds.center, bcoll.bounds.size, 0f, Vector2.down, .1f, JumpableGround);
Xinput =Input.GetAxisRaw("Horizontal");
rbody.velocity=new Vector2(Xinput * WalkSpeed, rbody.velocity.y);
if (Input.GetButtonDown("Jump") && isGrounded())
{
jump = true;
}
if(Input.GetButtonDown("Dash") && isGrounded() && CanDash==true)
{
if (DashCor != null)
{
StopCoroutine(DashCor);
}
DashCor = Dash(DashDuration, DashCD);
StartCoroutine(DashCor);
}
}
private void FixedUpdate()
{
if (IsGrounded && jump)
{
rbody.AddForce(Vector2.up * JumpForce, ForceMode2D.Impulse);
jump = false;
}
if (isDashing && IsGrounded)
{
rbody.AddForce(Vector2.left * DashForce, ForceMode2D.Impulse);
}
}
private bool isGrounded()
{
return Physics2D.BoxCast(bcoll.bounds.center, bcoll.bounds.size, 0f, Vector2.down, .1f, JumpableGround);
}
IEnumerator Dash(float DashDuration, float DashCD)
{
isDashing=true;
CanDash = false;
yield return new WaitForSeconds(DashDuration);
isDashing = false;
yield return new WaitForSeconds(DashCD);
CanDash = true;
}
}
Thanks everyone!
Comment