Home > Net >  Dashing in Unity 3D using Rigidbody
Dashing in Unity 3D using Rigidbody

Time:10-16

im currently making a fps game and i have a rigidbody character controller and im trying to make it dash towards the direction the player is facing however my current dash function makes it go downwards and goes very fast

any ideas for how i can either fix the dashing or make a new dash mechanism?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    float yaw = 0f, pitch = 0f;
    Rigidbody rb;

    public float walkSpeed = 5f, sensitivity = 2f;

    bool jumping = false;
    private float DashDistance = 5f;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        rb = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        if (Input.GetKey(KeyCode.Space) && Physics.Raycast(rb.transform.position, Vector3.down, 1   0.001f))
            rb.velocity = new Vector3(rb.velocity.x, 5f, rb.velocity.z);

        if (Physics.Raycast(rb.transform.position, Vector3.down, 1   0.001f))
            jumping = false;
        else
            jumping = true;

        if (jumping && Input.GetKey(KeyCode.LeftControl))
            Dash();

        Look();
    }

    private void FixedUpdate()
    {
        Movement();
    }

    void Look()
    {
        pitch -= Input.GetAxisRaw("Mouse Y") * sensitivity;
        pitch = Mathf.Clamp(pitch, -90f, 90f);
        yaw  = Input.GetAxisRaw("Mouse X") * sensitivity;
        Camera.main.transform.localRotation = Quaternion.Euler(pitch, yaw, 0f);
    }

    void Movement()
    {
        Vector2 axis = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")) * walkSpeed;
        Vector3 forward = new Vector3(-Camera.main.transform.right.z, 0f, Camera.main.transform.right.x);
        Vector3 wishDir = (forward * axis.x   Camera.main.transform.right * axis.y   Vector3.up * rb.velocity.y);
        rb.velocity = wishDir;
    }

    void Dash()
    {
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 1f, Input.GetAxis("Vertical"));
        Vector3 offset = new Vector3(movement.x * transform.position.x, movement.y * transform.position.y, movement.z * transform.position.z);

        rb.AddForce(transform.position   (offset * DashDistance), ForceMode.VelocityChange);
    }
}

CodePudding user response:

I think you should add force in the forward direction. AddForce(transform.forward * yourForceValue);

  • Related