Question by
unity_6BjdwqF9goTcRQ · Oct 19, 2020 at 09:32 AM ·
physicsrigidbody2dphysics2daddforce
How to make arrows fly to user mouse position?
I'm trying to make 2d platformer with bow shooting, but I can't understand how to make arrows fly to user mouse position. With my code arrows randomly fly either to correct point or to right from player.
if (Input.GetMouseButtonDown(0))
{
// set animation trigger(animation calls createArrow method)
keyDown = true;
animator.SetTrigger("StartShoot");
}
if (Input.GetMouseButtonUp(0) && arrow)
{
animator.ResetTrigger("StartShoot");
ShootArrow();
keyDown = false;
}
// while mouse key pressed arrow rotates after mouse position
if (keyDown && arrow)
{
Vector3 bowPosition = transform.position;
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = Camera.Instance.Distance;
Vector3 arrowDirection = UnityEngine.Camera.main.ScreenToWorldPoint(mousePosition) - bowPosition;
arrow.transform.right = arrowDirection;
}
void CreateArrow()
{
arrow = Instantiate(arrowPrefab, arrowSpawn.position, Quaternion.identity);
arrow.GetComponent<FixedJoint2D>().connectedBody = rigidboby;
}
void ShootArrow()
{
arrow.GetComponent<FixedJoint2D>().enabled = false;
arrow.GetComponent<Rigidbody2D>().AddForce(arrow.transform.right * arrowForce,ForceMode2D.Impulse);
arrow = null;
}
Comment