- Home /
The question is answered, right answer was accepted
Boomerang projectile doesn't return to player if the player has moved
I'm trying to create a projectle that fires from the player to the mouse position when the mouse is clicked, then back to the player. The script I have works fine if the player stays still but if the player moves then the projectile doesnt return once it has reached the click location. How can i fix this?
Heres my script so far
public class PlayerBoomerangAttack : MonoBehaviour
{
[SerializeField] float maxDistance = 6f;
[SerializeField] float speed = 6f;
bool boomerangInHand = true;
Vector3 target = Vector2.zero;
[SerializeField] GameObject boomerang = null;
GameObject boom = null;
bool targetReached = false;
Vector3 mousePos = Vector3.zero;
[SerializeField] float approxEqual = 1f;
Camera cam = null;
// Start is called before the first frame update
void Start()
{
cam = Camera.main;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonUp(0) && boomerangInHand)
{
BoomerangThrow();
}
}
void FixedUpdate()
{
if (!boomerangInHand)
{
BoomerangTravel();
}
}
void BoomerangThrow()
{
boomerangInHand = false;
targetReached = false;
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = transform.position.z;
boom = Instantiate(boomerang, transform.position, Quaternion.identity);
target = mousePos;
}
void BoomerangTravel()
{
if (!targetReached)
{
boom.GetComponent<Rigidbody2D>().velocity = (mousePos - transform.position).normalized * speed;
UnityEngine.Debug.Log(Vector2.Distance(boom.transform.position, target));
if (Vector2.Distance((Vector2)boom.transform.position, target) < approxEqual)
{
targetReached = true;
}
}
else
{
boom.GetComponent<Rigidbody2D>().velocity = (transform.position - boom.transform.position).normalized * speed;
if (Vector3.Distance(boom.transform.position, transform.position) < approxEqual)
{
boomerangInHand = true;
Destroy(boom);
}
}
}
}
Thank you.
Was the PlayerBoomerangAttack script added as a component to your player character?
Answer by dylan1812 · Jul 04, 2020 at 09:23 PM
I found the fix. I was using the current position of the player while the boomerang was in the air instead of the position of the player when the boomerang was released. This meant that the velocity vector of the boomerang wasn't going to the target and so was never returning.
Follow this Question
Related Questions
How do you make a projectile move in an arc? (2d) 1 Answer
How to shoot 2d projectile in multiple directions 1 by 1? Left Right Up Down 2 Answers
How do I get my character to shoot a projectile in the direction of the cursor? 1 Answer
Multiple Cars not working 1 Answer
How to get rotation for projectile to fire at cursor? 1 Answer