Search Unity

Help to How to Dash with Rigidbody3D

Discussion in 'Physics' started by le_tenebrae, Apr 16, 2019.

  1. le_tenebrae

    le_tenebrae

    Joined:
    Nov 25, 2017
    Posts:
    2
    Hello! I'm trying to do a mechanic for my demo game but I got stucked at the dash movement. I've made an isolated script that uses a coroutine in order to get a smooth transition, but nothing happens. I appreciate any help. Here it is:

    public class PlayerDash : MonoBehaviour
    {
    [SerializeField] float dashSpeed = 0.5f;
    [SerializeField] float dashDistance = 2f;

    new Rigidbody rigidbody;
    Vector3 movement;

    IEnumerator currentCoroutine;

    void Start() {

    rigidbody = GetComponent<Rigidbody>();
    }

    private void Update()
    {
    movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));

    if (Input.GetKeyDown(KeyCode.Space))
    {
    if (currentCoroutine != null)
    {
    StopCoroutine(currentCoroutine);
    }

    currentCoroutine = Dash(movement);
    StartCoroutine(currentCoroutine);
    }
    }

    IEnumerator Dash(Vector3 movement)
    {
    Vector3 destination = transform.position + movement * dashDistance;

    float remainDist = (transform.position - destination).sqrMagnitude;

    while (remainDist > float.Epsilon) {

    Vector3 newPos = Vector3.MoveTowards(transform.position, destination, dashSpeed * Time.deltaTime);
    rigidbody.MovePosition(transform.position + newPos);

    remainDist = (transform.position - destination).sqrMagnitude;

    Debug.Log(transform.position);

    yield return null;
    }
    }
    }​
     
  2. le_tenebrae

    le_tenebrae

    Joined:
    Nov 25, 2017
    Posts:
    2
    Nevermind, i made it.