Shooting A Projectile With an Arc
Hey all, I've been working on a script to launch a projectile in an arc and I've managed to cobble this together. EDIT: With the current code, the projectile is shot, but the calculation seems to be off. It will always overshoot the player. :/ EDIT 2: So I just calibrated the numbers and it seems to be fairly accurate now.
Help would be appreciated. Thanks In advance!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TripleArcShoot : MonoBehaviour {
public Vector3 targetPos;
public float speed = 10;
public float arcHeight = 3;
GameObject enemy;
public float DistanceFromPlayer, CoolDown;
public int AttackRadius;
public Vector3 InstPos;
public GameObject instantiatedObj;
public GameObject ProjectileGM;
private Vector3 ShootDir;
public float ShotSpeed;
private Vector3 EnemyPos;
private bool FL, FR;
void Start()
{
enemy = GameObject.FindGameObjectWithTag("Player");
targetPos = enemy.transform.position;
AttackRadius = 15;
CoolDown = 5;
}
void Update()
{
if (enemy != null)
{
DistanceFromPlayer = Vector3.Distance(enemy.transform.position, this.gameObject.transform.position);
if (DistanceFromPlayer <= AttackRadius)
{
Attack();
}
}
}
void Attack()
{
if (transform.position.x > enemy.transform.position.x)
{
InstPos = transform.position + new Vector3(-1.5f, 0f, 0f);
FL = true;
}
else
{
InstPos = transform.position + new Vector3(1.5f, 0f, 0f);
FR = true;
}
CoolDown -= Time.deltaTime;
if (CoolDown <= 0)
{
Debug.DrawLine(transform.position, enemy.transform.position, Color.cyan);
EnemyPos = enemy.transform.position - transform.position;
ShotSpeed = Mathf.Sqrt(Mathf.Abs(EnemyPos.x) / 0.0781678003f);
if (FR)
ShootDir = new Vector3(1.0f, 1.19175f, 0f);
else
ShootDir = new Vector3(-1.0f, 1.19175f, 0f);
instantiatedObj = (GameObject)Instantiate(ProjectileGM, InstPos, transform.rotation);
instantiatedObj.GetComponent<Rigidbody2D>().velocity = ShootDir.normalized * ShotSpeed * .80f;
Destroy(instantiatedObj, 4);
CoolDown = 5f;
}
}
static Quaternion LookAt2D(Vector2 forward)
{
return Quaternion.Euler(0, 0, Mathf.Atan2(forward.y, forward.x) * Mathf.Rad2Deg);
}
}
Go Back To Basics!!
Hey @meat5000
I went back to basics, this is what I've got now. The new issue is that the calculation causes it to consistently overshoot the player, in either direction. Thanks for your re$$anonymous$$der to strip it back to black :)
Yeah sorry didnt mean to seem condescending with the 'BiteSize' :P Sometimes that kind of stuff re$$anonymous$$ds us things we missed.
You seem to have a lot of hardcoded numbers in there, not to mention the $$anonymous$$athf.Abs. You know, at a glance these things are likely adding error.
Luckily there seem to be a lot of examples kicking around the internet. $$anonymous$$aybe not the best chosen battle to re-invent the wheel. Just be all, 'Ah thats how its done' and save your brainpower for the next task ;)
https://vilbeyli.github.io/Simple-Trajectory-$$anonymous$$otion-Example-Unity3D/