I am trying to make a dash/charge attack towards the cursor position with a max dash length and I am unsure how to do it as I am very new to Unity and coding in general.
It would be similar to this code except instead of teleporting the character would dash.
if (Physics.Raycast(ray, out hit, rayLength, layerMask) && Input.GetMouseButtonDown(1))
{
Vector3 hitPosition = new Vector3(hit.point.x, transform.position.y, hit.point.z);
player.transform.position = hitPosition;
}
CodePudding user response:
search youtube for "Different Ways to move an object in Unity". the soultion i suggest is to use AddForce instead of Transform.Position. Examples:
- using AddForce is just like kicking a ball in a direction.
- using transform.position is just like carrying the ball to the desired position.
CodePudding user response:
A solution using AddForce
could look something like this:
// Gets executed, on every left click
if (Input.GetMouseButtonDown(0))
{
float force = 5f;
Rigidbody2D rb = GetComponent<Rigidbody2D>();
// Gets the position of your mouse cursor in world space
Vector3 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rb.AddForce(direction * force, ForceMode2D.Impulse);
}
You would put this into the Update
Method.
Note however, that you should probably cache Camera.main
and the Rigidbody2D
.
Doing the lookups every frame is very inefficient.
You could / should also make the force
a field available in the inspector, so you can easily tweak it to your liking :)