So, I'm fairly new to unity and coding. I'm currently coding a top down 2d game and wanted to add a dash mechanic. Couldn't find a tutorial that really suited me, so I decided to code it myself. And well.. it didn't go too well for such an easy mechanic. So here I come asking for help to improve the shitcode I have produced. I feel like there's a much easier way to do it, but my lack of experience doesn't allow me to notice it. The code works just as I want it to now, but I'm looking to simplify my code with the same output.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
//run variables
Rigidbody2D rb;
float horizontal, vertical;
public float runSpeed;
//dash variables
public float dashSpeed;
public float startDashTime;
public float currentDashTimer;
public int dashDir;
bool isDashing;
bool shiftReplacement;
float shiftHolder;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
CheckIfShifted();
}
void FixedUpdate()
{
Dash();
}
public void CheckIfShifted()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
shiftReplacement = true;
shiftHolder = 0.08f;
}
else if(shiftHolder <= 0)
{
shiftReplacement = false;
}
shiftHolder -= Time.deltaTime;
}
public void Dash()
{
//check ín which direction player should dash
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
dashDir = 1;
}
else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
dashDir = 2;
}
else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
dashDir = 3;
}
else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
dashDir = 4;
}
//check if player has pressed dash button and initiate dash
if (shiftReplacement)
{
isDashing = true; //initiate dash
currentDashTimer = startDashTime;
rb.velocity = Vector2.zero;
}
//check if dash was initiated
if (isDashing == true)
{
if (dashDir == 1)
{
rb.velocity = transform.right * dashSpeed; //dash properties
}
else if (dashDir == 2)
{
rb.velocity = transform.right * -1 * dashSpeed; //dash properties
}
else if (dashDir == 3)
{
rb.velocity = transform.up * dashSpeed; //dash properties
}
else if (dashDir == 4)
{
rb.velocity = transform.up * dashSpeed * -1; //dash properties
}
Debug.Log("bich Im dashin'");
currentDashTimer -= Time.deltaTime;
}
if (currentDashTimer <= 0)
{
isDashing = false;
}
}
I've run into a variety of problems. For example like shift input not registering on time for the fixedupdate() to pick it up and or not registering at all. Or when I put everything inside the update() function my player didn't move. Any advice?
