making a boomerang effect in a 2D enviorment
I am trying to make the main character throw a projectile and it comes right back the way it came but i really dont know how to accomplish this, I thought maybe I can say if it reaches a distance from point 0,0 it can come back but that didnt work. i just want it to go in straight line forward and a straight line back. Im doing it in C# but any help will do.
Answer by UnityCoach · Feb 02, 2017 at 08:10 AM
Yes, the distance idea is right. You can do something like :
public float speed = 1f; // default speed 1 unit / second
public float distance = 5f; // default distance 5 units
public Transform boomerang; // the object you want to throw (assign from the scene)
private float _distance; // the distance it moves
private bool _back; // is it coming back
public void Shoot ()
{
_distance = 0; // resetting the distance
back = false; // resetting direction
enabled = true; // enabling the component, so turning the Update call on
}
private void Update ()
{
float travel = Time.deltaTime * speed;
if (!back)
{
boomerang.Translate(Vector3.forward * travel); // moves object
_distance += travel; // update distance
back = _distance >= distance; // goes back if distance reached
}
else
{
boomerang.Translate(Vector3.forward * -travel); // moves object
_distance -= travel; // update distance;
enabled = _distance > 0; // turning off when done
}
}
private void OnEnable ()
{
boomerang.gameObject.SetActive (true); // activating the object
}
private void OnDisable ()
{
boomerang.gameObject.SetActive (false);
}
Hello, how would I add this exactly? I created a new script and added the code, what do I do now? I know this is an old post, thanks.
Well, once the script is set up, with an object assigned, you need to trigger the Shoot
method. I guess using Input.GetButtonUp("")
would probably the best option to test it.
@UnityCoach , what about using an animation? is'n it better than using a script?
@Persian$$anonymous$$iller You're right, using animations and Animator State $$anonymous$$achines would probably give better performances.
Your answer
Follow this Question
Related Questions
Can't make my AI shoot projectiles with raycast 0 Answers
How can i make the right choice of implementation of my shooting fire script ? 1 Answer
Projectile trajectory based on angle 0 Answers
Shoot towards target 0 Answers
Shooting sideways? 1 Answer