--------I have a system set up where a central turret spawns a projectile aimed at the mouse cursor whenever the player presses a button. I’m trying to make it so that the projectiles detonate where the cursor was when they were launched. I have tried a few different approaches, but can’t get them to work right. ATM I have a it working for exactly the screen scale of the game preview window, but resizing it distorts the detonation distance and de-syncs it with the mouse point (Also it’s pretty hacky IMO). Does anyone know what the best way to do this is? My current projectile code is here:
public int speed;
public GameObject shockwave;
Vector3 object_pos;
Vector3 mouse_pos;
float lifespan;
public GameObject shipExplosion;
public GameObject energyDrop;
int timer = 0;
void Start () {
mouse_pos = Input.mousePosition;
object_pos = Camera.main.WorldToScreenPoint(rigidbody2D.transform.position);
mouse_pos.x = mouse_pos.x - object_pos.x;
mouse_pos.y = mouse_pos.y - object_pos.y;
//Calculates the distance from the spawn point to cursor
lifespan = Mathf.Sqrt(Mathf.Abs(mouse_pos.x) * Mathf.Abs(mouse_pos.x) + Mathf.Abs(mouse_pos.y) * Mathf.Abs(mouse_pos.y));
//Calculates time for the projectile to reach the cursor point based on the projectile speed,
//then multiplies by 1.5 because that scale works with the window :/
lifespan = lifespan / speed * 1.5F;
//Calculates the angle and velocities to launch at
float angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x);
float xVel = speed * Mathf.Cos(angle);
float yVel = speed * Mathf.Sin(angle);
rigidbody2D.velocity = new Vector2(xVel, yVel);
}
void Update () {
timer++;
//If the time it's been alive is greater then the lifespan set above, detonate
if (timer > lifespan)
{
Instantiate(shockwave, new Vector3(transform.position.x, transform.position.y, 0), new Quaternion(0, 0, 0, 1));
Destroy(this.gameObject);
}
}