Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

c# - Dashing in Unity 2D using the Rigidbody Component

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

public class Movement : MonoBehaviour
{

    public float movementSpeed;
    public Rigidbody2D Rigidbody;
    private Vector2 moveDirection;
    public Transform Player;
    void Start()
    {
        
    }

    void Update()
    {
        ProcessInputs();
    } void FixedUpdate()
    {
        move();
    }
    void ProcessInputs()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");

        moveDirection = new Vector2(moveX, moveY).normalized;
    }
     void move()
    {
        Rigidbody.velocity = new Vector2(moveDirection.x * movementSpeed, moveDirection.y * movementSpeed);
    }

}


So i needed some tips so i thoght id ask here, i wanted to implement dashing in my Top-Down-Shooter but i didnt find any code on Youtube that would properly work with my code i have also tried moveing the players position +2 to the wanted direction but i couldnt work it out. id be happy if yall could help me.

question from:https://stackoverflow.com/questions/65900689/dashing-in-unity-2d-using-the-rigidbody-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Nice that you are using FixedUpdate() for physics - many beginners use that wrong. However do not set velocity manually. Use AddForce. It will effectively set the velocity but automatically takes the objects mass into account and allows to speed up instead of instantly being at speed. That is the more logical approach since you move in a direction by applying forces to your body.

For Dashing, you could add a significantly higher force for a small number of Physics frames (aka small number of FixedUpdate calls). You can use a countdown which you set to a number when the chaarcter hsould start dashing. In the FixedUpdate you decrement the counter and as long as it is >0 you apply the dashing force.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...