Move GameObject in a direction of a mouse but longer
I have a turret that is firing in the direction of my mouse. My current code is:
void Fire()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
direction = Vector3.MoveTowards(projectile.transform.position, mousePos, 50);
}
void Update()
{
proj.transform.position = Vector3.MoveTowards(projectile.transform.position, direction, speed * Time.deltaTime);
}
The projectile moves to where mouse position was once I fired it, but then stops. I need it to go on moving in the same direction even when it reaches the position where mouse was at the moment of fire. In other words I need either to prolong the distance between mouse position and projectile start position or just move it infinitely in the same direction.
Answer by ricke44654 · May 25, 2016 at 01:42 AM
I think to make this work the way you want, I would just adjust the position of the projectile manually in the Update function. You've got your direction set from the Fire function, so instead of using MoveTowards in Update, you'd do something like this:
proj.transform.position += (direction * speed * Time.deltaTime);
I setup a little test project to test it out myself and duplicated what you were seeing. Then I changed it to the above code and that seemed to do the trick. You'll need some way to dispose / disable the object after some condition is met.
One possibility might be a sphere collider around your turret set to the maximum range of a shot. The collider could be set as a Trigger collider and you could use the OnTriggerExit event to determine when the bullet leaves the collider. Never tried it as I'm still Unity noobish, but seems like that could work.
This is behaving wrong when working with negative values. In certain conditions projectiles strike in the opposite direction of where they're supposed to, and sometimes trajectory is very distorted. But thanks for answering.
For now projectiles are destroyed when they are not seen by any camera.
Your answer
Follow this Question
Related Questions
Problem with destroying a gameobject 2 Answers
Locking facing direction or changing it after following the mouse position 0 Answers
Very weird. Transform position is at two places at the same time. 1 Answer
Moving GameObject slowly OnTriggerEnter 1 Answer
Gameobject doesnt move after build 0 Answers