- Home /
How do I stop a 2D projectile when it reaches a point
I have a weapon that fires projectiles where you aim with some inaccuracy by getting a vector and I want it to stop close to the point I click but I don't even know where to start, here's my code so far-
void Start()
{
zx = Random.Range(-spread, spread) / 200;
zy = Random.Range(-spread, spread) / 100;
Vector2 heading = GameObject.FindGameObjectWithTag("target").transform.position - transform.position;
vector = heading.normalized;
// find rotatio
angle = Mathf.Atan2(heading.y, heading.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
}
void Update()
{
transform.localPosition += new Vector3(vector.x + zx,vector.y + zy) * speed;
}
cleaned the formatting, you don't need to add the ` for pasting blocks of code btw
Answer by tormentoarmagedoom · Jan 22, 2019 at 03:48 PM
Good day.
Its simple. I did something like this in the past.
Make the bullet a prefab, whith a script wich:
-know the real destination point (we call from now "realdest")
-Calculate a little random destination for the inacuraccy.
-Moves the bullet (itself) to this new destination dest.
-Reads the position of the bullet every frame (or every 0.5 seconds or something liek this)
-Store this position in a Vector3 variable called "LastPos"
-Then each update check for this 2 distances (LastPos-realdest) and (tranform.position-realdest)
-During all bullet travel, (LastPos-dest) is always higher than (tranform.position-dest) becuase you are approaching to dest
-But when (LastPos-dest) < (tranform.position-dest) it means you reached the closest point to the real destination of your trajectory, so you can destriy the bullet (itself)
EASY! :D
Good luck! Bye!
Answer by xxmariofer · Jan 22, 2019 at 03:24 PM
Why not just an if in the update comparing if the transform.localposition is more or equals to the desired position? then just set velocity to 0
I can't use equals because of the inaccuracy or more because you can shoot in any direction
Answer by R4y-GM · Jan 22, 2019 at 03:43 PM
there are a lot of possibilites to stop it you can add a time.timescale = 0 or a OnCollisionEnter(Collision collision) and put it if(collision.gameobject.tag =="your projectile tag" ) to collide you must do a box with a collider
Your answer
Follow this Question
Related Questions
How to shoot a bullet and animate at the same time??? Its a 2D shooter c# 3 Answers
How to make projectiles shoot diagonally? 1 Answer
How do i adjust the projectile path and direction? 1 Answer
2d direcitonal shooting 0 Answers
How can I get my bullet to shoot the other way when I face left. 2d 1 Answer