Search Unity

2D Player dash towards mouse click position

Discussion in '2D' started by eyoleet, Aug 3, 2019.

  1. eyoleet

    eyoleet

    Joined:
    Aug 3, 2019
    Posts:
    1
    Hi, I'm trying to create a dash similar to the one used in Katana Zero, in which on clicking the mouse button to attack the player does a slight dash in that direction.

    I'm trying to achieve this using AddForce, the code I'm using seems to work but the player seems to move first along the X axis and then up the Y axis towards the mouseclick point. Also, the force added isn't equal at all points, clicking the mouse directly above the player adds a lot more force than when clicking at an angle.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DashToMouse : MonoBehaviour
    6. {
    7.     [SerializeField] private float dashSpeed;
    8.     [SerializeField] private float startDashTime;
    9.  
    10.     private float dashTime;
    11.  
    12.     private Rigidbody2D rd2d;
    13.     private Animator anim;
    14.  
    15.     private Camera cam;
    16.  
    17.  
    18.     // Start is called before the first frame update
    19.     void Start()
    20.     {
    21.         rd2d = GetComponent<Rigidbody2D>();
    22.         anim = GetComponent<Animator>();
    23.         cam = Camera.main;
    24.     }
    25.  
    26.     private void FixedUpdate()
    27.     {
    28.         DashToPoint();
    29.     }
    30.  
    31.     protected void DashToPoint()
    32.     {
    33.         if (Input.GetMouseButtonDown(0))
    34.         {
    35.             Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    36.             mousePos.z = 0;
    37.             Vector3 difference = mousePos - transform.position;
    38.             difference = difference.normalized;
    39.             float angle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    40.             Vector3 dir = Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right;
    41.  
    42.  
    43.  
    44.             dashTime = startDashTime;
    45.             while (dashTime > 0)
    46.             {
    47.                 anim.SetTrigger("ground up swipe");
    48.                 rd2d.AddForce(dir * dashSpeed);
    49.                 dashTime = dashTime - Time.deltaTime;
    50.             }
    51.         }
    52.     }
    53. }
    54.  
    This is my code. Any help appreciated! Thanks :)