I am new to programming and was wondering how I could make my "dash" make me move forward. I watched an online tutorial on how to make a dash work but after trying, the dash would only push me at all if I had written rb.velocity = Vector2.up * dashSpeed;. Currently, when I press the dash key, my character's gravity slows down for a second but no movement is made. Can I please get some help in making it push my character?
If you need clarification, please ask!
PS: Sorry for the long script, all my player control is in here.
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
//Player Movement
public float speed;
public float jumpForce;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
public float dashSpeed;
public float startDashTime;
public Animator animator;
private Rigidbody2D rb;
private float moveInput;
private bool isGrounded;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private float dashTime;
private int direction;
void Start()
{
animator.GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
dashTime = startDashTime;
}
void FixedUpdate()
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
void Update()
{
// Moving
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
animator.SetBool("Moving", true);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
animator.SetBool("Moving", true);
}
else
{
animator.SetBool("Moving", false);
}
// Jumping
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("IsJumping");
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
if (isGrounded == false)
{
animator.SetBool("Grounded", false);
}
if (isGrounded == true)
{
animator.SetBool("Grounded", true);
}
// Dashing
if(direction == 0)
{
if(Input.GetKeyDown(KeyCode.LeftShift))
{
if ((transform.rotation.eulerAngles.y == 180))
{
Dashleft();
}
else
{
DashRight();
}
}
}
else
{
if(dashTime <= 0)
{
direction = 0;
dashTime = startDashTime;
}
else
{
dashTime -= Time.deltaTime;
}
}
}
void Dashleft()
{
rb.velocity = Vector2.left * dashSpeed;
}
void DashRight()
{
rb.velocity = Vector2.right * dashSpeed;
}
}
The problem is that your horizontal velocity is being controlled in FixedUpdate()
It is being overriden in every physics frame, so when you change velocity in DashLeft() or DashRight() methods, velocity is being reset in this line rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
You can do something like this:
if (dashTime <= 0)
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
So you control your velocity by Input only if player is not dashing
Related
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Movement")]
private float moveSpeed;
public float walkSpeed;
public float sprintSpeed;
public bool sliding;
public bool sprinting;
public float groundDrag;
[Header("Jumping")]
public float jumpForce;
public float jumpCooldown;
public float airMultiplier;
bool readyToJump;
[Header("Crouching")]
public float crouchSpeed;
public float crouchYScale;
private float startYScale;
[Header("Keybinds")]
public KeyCode jumpKey = KeyCode.Space;
public KeyCode sprintKey = KeyCode.LeftShift;
public KeyCode crouchKey = KeyCode.LeftControl;
[Header("Ground Check")]
public float playerHeight;
public LayerMask whatIsGround;
bool grounded;
[Header("Slope Handling")]
public float maxSlopeAngle;
private RaycastHit slopeHit;
private bool exitingSlope;
[Header("Sliding")]
public float maxSlideTime;
public float slideForce;
private float slideTimer;
public float slideSpeed;
public float slideYScale;
[Header("References")]
public Transform orientation;
private Rigidbody rb;
[Header("Input")]
private float horizontalInput;
private float verticalInput;
Vector3 moveDirection;
public MovementState state;
public enum MovementState
{
walking,
sprinting,
crouching,
sliding,
air
}
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
readyToJump = true;
startYScale = transform.localScale.y;
}
private void Update()
{
// ground check
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
MyInput();
SpeedControl();
StateHandler();
if (Input.GetKeyUp(sprintKey) || Input.GetKeyUp(KeyCode.W))
sprinting = false;
// handle drag
if (grounded)
rb.drag = groundDrag;
else
rb.drag = 0;
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown(crouchKey) && sprinting)
StartSlide();
if (Input.GetKeyUp(crouchKey) && sliding)
StopSlide();
}
private void FixedUpdate()
{
MovePlayer();
if (sliding)
SlidingMovement();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
// when to jump
if (Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
// start crouch
if (Input.GetKeyDown(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
rb.AddForce(Vector3.down * 5f, ForceMode.Impulse);
}
if (Input.GetKeyDown(crouchKey) && sprinting)
{
transform.localScale = new Vector3(transform.localScale.x, slideYScale, transform.localScale.z);
rb.AddForce(Vector3.down * 5f, ForceMode.Impulse);
sliding = true;
moveSpeed = slideSpeed;
}
// stop crouch
if (Input.GetKeyUp(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
sliding = false;
}
}
private void StateHandler()
{
// Mode - Crouching
if (Input.GetKey(crouchKey))
{
state = MovementState.crouching;
moveSpeed = crouchSpeed;
}
// Mode - Sliding
if(Input.GetKey(crouchKey) && sprinting)
{
state = MovementState.sliding;
moveSpeed = slideSpeed;
}
// Mode - Sprinting
else if (grounded && Input.GetKey(sprintKey) && Input.GetKey(KeyCode.W))
{
state = MovementState.sprinting;
moveSpeed = sprintSpeed;
sprinting = true;
}
// Mode - Walking
else if (grounded)
{
state = MovementState.walking;
moveSpeed = walkSpeed;
}
// Mode - Air
else
{
state = MovementState.air;
}
}
private void MovePlayer()
{
// calculate movement direction
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
// on slope
if (OnSlope() && !exitingSlope)
{
rb.AddForce(GetSlopeMoveDirection() * moveSpeed * 20f, ForceMode.Force);
if (rb.velocity.y > 0)
rb.AddForce(Vector3.down * 80f, ForceMode.Force);
}
// on ground
else if (grounded)
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
// in air
else if (!grounded)
rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
// turn gravity off while on slope
rb.useGravity = !OnSlope();
}
private void SpeedControl()
{
// limiting speed on slope
if (OnSlope() && !exitingSlope)
{
if (rb.velocity.magnitude > moveSpeed)
rb.velocity = rb.velocity.normalized * moveSpeed;
}
// limiting speed on ground or in air
else
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
// limit velocity if needed
if (flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}
}
private void Jump()
{
exitingSlope = true;
// reset y velocity
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
private void ResetJump()
{
readyToJump = true;
exitingSlope = false;
}
private bool OnSlope()
{
if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.3f))
{
float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
return angle < maxSlopeAngle && angle != 0;
}
return false;
}
private Vector3 GetSlopeMoveDirection()
{
return Vector3.ProjectOnPlane(moveDirection, slopeHit.normal).normalized;
}
private void StartSlide()
{
sliding = true;
transform.localScale = new Vector3(transform.localScale.x, slideYScale, transform.localScale.z);
rb.AddForce(Vector3.down * 5f, ForceMode.Impulse);
slideTimer = maxSlideTime;
}
private void SlidingMovement()
{
Vector3 inputDirection = orientation.forward;
rb.AddForce(inputDirection.normalized * slideForce, ForceMode.Force);
slideTimer -= Time.deltaTime;
if (slideTimer <= 0)
StopSlide();
}
private void StopSlide()
{
sliding = false;
transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
}
}
I have been trying for a very long time to fix this, although I'm not the best at coding. I decided to come onto stack overflow for some help. Thank you to everyone who tries to solves this problem :D. As the titles states everything here works, excluding the crouching, when I press ctrl my moveSpeed does not change to my crouchSpeed...
I have coded the unity movement for my character. I made it so they can wall run bit it seems that wall running is somehow making my character walk weird. After wall running (if I wall run with the wall on my right) it will apply a force 90 degrees when I'm walking on the ground. The unknown force changes when each button is pressed (is W then apply both the W force and a force pushing it to the right). And the same happens with running on the left wall but it is at a -90 degree angle. Please help I've been stuck on this for a whole week. Thanks
This is the wall running code
using System.Collections.Generic;
using UnityEngine;
public class MoveChar : MonoBehaviour
{
[Header("Movement")]
float moveSpeed;
[SerializeField] float walkSpeed;
[SerializeField] float sprintSpeed;
[SerializeField] float slideSpeed;
[SerializeField] float wallRunSpeed;
float desiredMoveSpeed;
float lastDesiredMoveSpeed;
[SerializeField] float groundDrag;
[Header("Jumping")]
[SerializeField] float jumpForce;
[SerializeField] float jumpCoolDown;
[SerializeField] float airMultiplier;
bool readyToJump;
[HideInInspector] public bool doubleJump;
[Header("Crouching")]
[SerializeField] float crouchSpeed;
[SerializeField] float crouchYScale;
float crouchYStart;
bool exitingJump;
[Header("Slope Check")]
[SerializeField] float maxSlope;
RaycastHit slopeHit;
[Header("Ground Check")]
[SerializeField] float playerHeight;
[SerializeField] LayerMask whatIsGround;
bool grounded;
[Header("Keybinds")]
KeyCode jumpKey = KeyCode.Space;
KeyCode walkKey = KeyCode.LeftShift;
KeyCode crouchKey = KeyCode.C;
[SerializeField] Transform orientation;
[SerializeField] Transform camRotate;
float horizontalInput;
float verticalInput;
Vector3 moveDirection;
Rigidbody rb;
MovementState state;
enum MovementState
{
walking,
sprinting,
crouching,
sliding,
wallRunning,
air
}
[HideInInspector] public bool sliding;
[HideInInspector] public bool wallRunning;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
ResetJump();
crouchYStart = transform.localScale.y;
}
// Update is called once per frame
void Update()
{
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
MyInput();
SpeedControl();
StateHandler();
if (grounded)
{
rb.drag = groundDrag;
}
else
{
rb.drag = 0;
}
}
private void FixedUpdate()
{
MovePlayer();
}
void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown(jumpKey) && readyToJump && (grounded || doubleJump))
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCoolDown);
}
if (grounded && !Input.GetKey(jumpKey))
{
doubleJump = false;
}
if (Input.GetKeyDown(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
rb.AddForce(Vector3.down * 5f, ForceMode.Impulse);
}
if (Input.GetKeyUp(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, crouchYStart, transform.localScale.z);
}
}
void StateHandler()
{
if (wallRunning)
{
state = MovementState.wallRunning;
desiredMoveSpeed = wallRunSpeed;
doubleJump = false;
}
if (sliding)
{
state = MovementState.sliding;
if (OnSlope() && rb.velocity.y < 0.1f)
{
desiredMoveSpeed = slideSpeed;
}
else
{
desiredMoveSpeed = sprintSpeed;
}
}
else if (Input.GetKey(crouchKey))
{
state = MovementState.crouching;
desiredMoveSpeed = crouchSpeed;
}
else if (grounded && Input.GetKey(walkKey))
{
state = MovementState.walking;
desiredMoveSpeed = walkSpeed;
}
else if (grounded)
{
state = MovementState.sprinting;
desiredMoveSpeed = sprintSpeed;
}
else
{
state = MovementState.air;
}
if (Mathf.Abs(desiredMoveSpeed - lastDesiredMoveSpeed) > 4f && moveSpeed != 0)
{
StopAllCoroutines();
StartCoroutine(SmoothlyLerpMoveSpeed());
}
else
{
moveSpeed = desiredMoveSpeed;
}
lastDesiredMoveSpeed = desiredMoveSpeed;
}
IEnumerator SmoothlyLerpMoveSpeed()
{
float time = 0;
float difference = Mathf.Abs(desiredMoveSpeed - moveSpeed);
float startValue = moveSpeed;
while (time < difference)
{
moveSpeed = Mathf.Lerp(startValue, desiredMoveSpeed, time / difference);
time += Time.deltaTime;
yield return null;
}
moveSpeed = desiredMoveSpeed;
}
void MovePlayer()
{
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
if (OnSlope() && !exitingJump)
{
rb.AddForce(GetSlopeMoveDirection(moveDirection) * moveSpeed * 20f, ForceMode.Force);
if (rb.velocity.y > 0)
{
rb.AddForce(Vector3.down * 80f, ForceMode.Force);
}
}
else if (grounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
}
else if (!grounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
}
if (!wallRunning)
{
rb.useGravity = !OnSlope();
}
}
void SpeedControl()
{
if (OnSlope() && !exitingJump)
{
if (rb.velocity.magnitude > moveSpeed)
{
rb.velocity = rb.velocity.normalized * moveSpeed;
}
}
else
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
if (flatVel.magnitude > moveSpeed)
{
Vector3 limitVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitVel.x, rb.velocity.y, limitVel.z);
}
}
}
void Jump()
{
exitingJump = true;
rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
doubleJump = !doubleJump;
}
void ResetJump()
{
readyToJump = true;
exitingJump = false;
}
public bool OnSlope()
{
if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.3f))
{
float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
return angle < maxSlope && angle != 0;
}
return false;
}
public Vector3 GetSlopeMoveDirection(Vector3 direction)
{
return Vector3.ProjectOnPlane(direction, slopeHit.normal).normalized;
}
}
This is the wall running code
using System.Collections.Generic;
using UnityEngine;
public class WallRunning : MonoBehaviour
{
[Header("Wallrunning")]
[SerializeField] LayerMask whatIsRunAble;
[SerializeField] LayerMask whatIsGround;
[SerializeField] float wallRunForce;
[SerializeField] float wallRunUpForce;
[SerializeField] float wallRunSideForce;
[SerializeField] float wallClimbSpeed;
[Header("Input")]
KeyCode jumpKey = KeyCode.Space;
float horizontalInput;
float verticalInput;
[Header("Detection")]
[SerializeField] float wallCheckDistance;
[SerializeField] float minJumpHeight;
RaycastHit leftWallHit;
RaycastHit rightWallHit;
bool wallLeft;
bool wallRight;
[Header("Exiting")]
[SerializeField] float exitWallTime;
bool exitingWall;
float exitWallTimer;
[Header("Gravity")]
[SerializeField] bool useGravity;
[SerializeField] float gravityCounterForce;
[Header("References")]
[SerializeField] Transform orientation;
MoveChar mc;
Rigidbody rb;
[SerializeField] Transform cam;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
mc = GetComponent<MoveChar>();
}
// Update is called once per frame
void Update()
{
CheckForWall();
StateMachine();
}
private void FixedUpdate()
{
if (mc.wallRunning)
{
WallRunMove();
}
}
void CheckForWall()
{
wallRight = Physics.Raycast(transform.position, orientation.right, out rightWallHit, wallCheckDistance, whatIsRunAble);
wallLeft = Physics.Raycast(transform.position, -orientation.right, out leftWallHit, wallCheckDistance, whatIsRunAble);
}
bool AboveGround()
{
return !Physics.Raycast(transform.position, Vector3.down, minJumpHeight, whatIsGround);
}
void StateMachine()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
if ((wallLeft || wallRight) && verticalInput > 0 && AboveGround() && !exitingWall)
{
if (Input.GetKeyDown(jumpKey))
{
WallJump();
}
}
if ((wallLeft || wallRight) && verticalInput > 0 && AboveGround() && !exitingWall)
{
if (!mc.wallRunning)
{
StartWallRun();
}
}
else if (exitingWall)
{
if (mc.wallRunning)
{
StopWallRun();
}
if (exitWallTimer > 0)
{
exitWallTimer -= Time.deltaTime;
}
if (exitWallTimer <= 0)
{
exitingWall = false;
}
}
else
{
if (mc.wallRunning)
{
StopWallRun();
}
}
}
void StartWallRun()
{
mc.wallRunning = true;
rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
if (wallRight)
{
cam.localRotation = Quaternion.Euler(0, 0, 10f);
}
if (wallLeft)
{
cam.localRotation = Quaternion.Euler(0, 0, -10f);
}
}
void WallRunMove()
{
rb.useGravity = useGravity;
Vector3 wallNormal = wallRight ? rightWallHit.normal : leftWallHit.normal;
Vector3 wallForward = Vector3.Cross(wallNormal, transform.up.normalized);
if ((orientation.forward - wallForward).magnitude > (orientation.forward - -wallForward).magnitude)
{
wallForward = -wallForward;
}
rb.AddForce(wallForward * wallRunForce, ForceMode.Force);
/*if (!(wallLeft && horizontalInput > 0) && !(wallRight && horizontalInput < 0))
{
rb.AddForce(-wallNormal * 100, ForceMode.Force);
}
if (useGravity)
{
rb.AddForce(transform.up * gravityCounterForce, ForceMode.Force);
}*/
}
void StopWallRun()
{
mc.wallRunning = false;
cam.localRotation = Quaternion.Euler(0, 0, 0);
}
void WallJump()
{
exitingWall = true;
exitWallTimer = exitWallTime;
Vector3 wallNormal = wallRight ? rightWallHit.normal : leftWallHit.normal;
Vector3 forceToApply = transform.up * wallRunUpForce + wallNormal * wallRunSideForce;
rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
rb.AddForce(forceToApply, ForceMode.Impulse);
mc.doubleJump = !mc.doubleJump;
}
}
Thank you soooooooo much for any help
I created a script to make the character dash to the left or to the right but no matter what I do the character won't get pushed horizontally, when I switch it so that the character is pushed upwards the vector does work.
at the vectors there are two different ways of using methods because i tried both to see if either would work but they didn't.
here's the script.
public float speed;
public float jumpForce;
public float inputHorizontal;
public Rigidbody2D rb;
public float checkRadius;
bool isGrounded;
public Transform groundCheck;
public LayerMask whatIsGround;
public float dashSpeed;
public float dashTimeValue;
private float dashTime;
int extraJumps;
public int extraJumpsValue;
private bool facingRight = true;
void Start()
{
rb = GetComponent<Rigidbody2D>();
dashTime = dashTimeValue;
}
void Update()
{
if(isGrounded == true)
{
extraJumps = extraJumpsValue;
}
if(Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
{
rb.velocity = new Vector2(0f, jumpForce);
extraJumps = extraJumps - 1;
}
if(Input.GetKeyDown(KeyCode.F))
{
if(dashTime == dashTimeValue && facingRight == true)
{
rb.velocity = new Vector2(dashSpeed, 1f);
Debug.Log("eh");
dashTime -= Time.deltaTime;
}else if(dashTime == dashTimeValue && facingRight == false)
{
rb.velocity = Vector2.left * dashSpeed;
Debug.Log("eh");
dashTime -= Time.deltaTime;
}
dashTime = dashTimeValue;
}
}
void FixedUpdate()
{
inputHorizontal = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(inputHorizontal * speed, rb.velocity.y);
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
if(facingRight == false && inputHorizontal > 0){
Flip();
}else if(facingRight == true && inputHorizontal < 0){
Flip();
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
Recently I have been Frankensteining code I've found online together and I am struggling to implement the dash correctly. In its current state, whenever my character jumps and then uses his dash, he gets caught in the air as if the dash didn't move him. Obviously this inst intended and I was wondering how I could fix this. Also, how could I include a cool down system to my dash ability. I've tried using various sources for cool down scripts but they always seem to have a downside.
Thanks in advance!
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
//Player Movement
public float speed;
public float jumpForce;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
public float dashSpeed;
public float startDashTime;
private float timeStamp = 0;
public Animator animator;
private Rigidbody2D rb;
private float moveInput;
private bool isGrounded;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private float dashTime;
public int direction;
void Start()
{
animator.GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
dashTime = startDashTime;
}
void FixedUpdate()
{
moveInput = Input.GetAxisRaw("Horizontal");
if (direction < 1)
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
void Update()
{
// Moving
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
animator.SetBool("Moving", true);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
animator.SetBool("Moving", true);
}
else
{
animator.SetBool("Moving", false);
}
// Jumping
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("IsJumping");
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
if (isGrounded == false)
{
animator.SetBool("Grounded", false);
}
if (isGrounded == true)
{
animator.SetBool("Grounded", true);
}
// Dashing
if (direction == 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if ((transform.rotation.eulerAngles.y == 180))
{
Dashleft();
}
else
{
DashRight();
}
}
}
else
{
if (dashTime <= 0)
{
direction = 0;
dashTime = startDashTime;
rb.velocity = Vector2.zero;
}
else
{
dashTime -= Time.deltaTime;
}
}
void Dashleft()
{
direction = 1;
rb.velocity = Vector2.left * dashSpeed;
}
void DashRight()
{
direction = 1;
rb.velocity = Vector2.right * dashSpeed;
}
}
}
I am new to coding. I've been trying to Frankenstein basic tutorials into something of my own and it seems ive finally hit a wall. I'm really not sure what is causing this and would like some help to weed out the problem.
at the moment when I press the dash button (left shift) my character dashes in the direction he is facing but for a random duration. I would like it to be consistent and working properly.
Thanks in advance!
PS: Sorry for the long script, it contains everything to do with player movment.
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
//Player Movement
public float speed;
public float jumpForce;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
public float dashSpeed;
public float startDashTime;
public float dashCooldownTime = 2;
private float nextFireTime = 0;
public Animator animator;
private Rigidbody2D rb;
private float moveInput;
private bool isGrounded;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private float dashTime;
public int direction;
void Start()
{
animator.GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
dashTime = startDashTime;
}
void FixedUpdate()
{
moveInput = Input.GetAxisRaw("Horizontal");
if (direction < 1 )
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
void Update()
{
// Moving
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
animator.SetBool("Moving", true);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
animator.SetBool("Moving", true);
}
else
{
animator.SetBool("Moving", false);
}
// Jumping
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("IsJumping");
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
if (isGrounded == false)
{
animator.SetBool("Grounded", false);
}
if (isGrounded == true)
{
animator.SetBool("Grounded", true);
}
// Dashing
if (Time.time > nextFireTime)
{
if (direction == 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
UnityEngine.Debug.Log("beaners");
nextFireTime = Time.time + dashCooldownTime;
if ((transform.rotation.eulerAngles.y == 180))
{
Dashleft();
}
else
{
DashRight();
}
}
}
}
else
{
if(dashTime <= 0)
{
direction = 0;
dashTime = startDashTime;
}
else
{
dashTime -= Time.deltaTime;
}
}
}
void Dashleft()
{
direction = 1;
rb.velocity = Vector2.left * dashSpeed;
}
void DashRight()
{
direction = 1;
rb.velocity = Vector2.right * dashSpeed;
}
}
Random duration is because of the use of Rigidbody2D.
See in Unity Rigidbody2D is responsible for each and every single physical interaction. It mean forces from player like player movement and forces from your environment like friction and collision.
Here what is happening is that when your player is dashing there is also player movement force, which is also applied on your player's Rigidbody2d. And friction of ground on which your player is running/dashing on.
I've added a comment on parts that I've changed.
Updated part of your script:
private bool isDashing;
.
.
.
void Update()
{
//Added: putting a Condition to check if you player is not dashing, if it is then
//player won't be able to do anything, As I've scene and done in many games. if you
//don't want this remove it and see what happens, this is not tested so sorry if there
//is something that is not working as intended.
//dashing condition check
if(!isDashing)
{
// Moving
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
animator.SetBool("Moving", true);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
animator.SetBool("Moving", true);
}
else
{
animator.SetBool("Moving", false);
}
// Jumping
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("IsJumping");
isJumping = true;
jumpTimeCounter = jumpTime;
//Changed: use Add force method instead of changing the velocity.
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
//rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
//Changed: Same this rb.AddForce...
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
//rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
if (isGrounded == false)
{
animator.SetBool("Grounded", false);
}
if (isGrounded == true)
{
animator.SetBool("Grounded", true);
}
}
//dashing condition ends
// Dashing
if (Time.time > nextFireTime)
{
//Here your Dash timer ends.
isDashing = false;
if (direction == 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
UnityEngine.Debug.Log("beaners");
nextFireTime = Time.time + dashCooldownTime;
//Here your Dash timer Starts.
isDashing = true;
if ((transform.rotation.eulerAngles.y == 180))
{
Dashleft();
}
else
{
DashRight();
}
}
}
}
else
{
if(dashTime <= 0)
{
direction = 0;
dashTime = startDashTime;
}
else
{
dashTime -= Time.deltaTime;
}
}
}
visit Unity - Scripting API: Rigidbody2D.AddForce hope it helps.
Happy Coding