I'm trying to do my first platformer at Unity. And have some problem with projectile. I found a tutorial, how create a projectile moving, but without trigger on Fire button. It is possible to change this script for firing on button? I tried to make it with if statement, but then projectile move only ones, it doesn't fly :(
public class projectile : MonoBehaviour
{
public GameObject player;
public GameObject target;
private float playerX;
private float targetX;
private float dist;
private float nextX;
private float baseY;
private float height;
public float speed = 10f;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
target = GameObject.FindGameObjectWithTag("Enemy");
}
void Update()
{
Fire();
}
public static Quaternion LookAtTarget(Vector2 rotation)
{
return Quaternion.Euler(0, 0, Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg);
}
private void Fire()
{
playerX = player.transform.position.x;
targetX = target.transform.position.x;
dist = targetX - playerX;
nextX = Mathf.MoveTowards(transform.position.x, targetX, speed * Time.deltaTime);
baseY = Mathf.Lerp(player.transform.position.y, target.transform.position.y, (nextX - playerX) / dist);
height = 2 * (nextX - playerX) * (nextX - targetX) / (-0.25f * dist * dist);
Vector3 movePosition = new Vector3(nextX, baseY + height, transform.position.z);
transform.rotation = LookAtTarget(movePosition - transform.position);
if (transform.position == target.transform.position)
{
Destroy(gameObject);
}
}
}
What's in the
Updatemethod happens every frame, so you need to create a manual trigger (bool isFired).The idea is that when
isFiredis false, nothing happens. Then, whenisFiredturns to true, the projectile starts moving.Your
Firemethod actually makes the projectile move so you should rename it toMoveand inUpdateyou callMoveonly when the projectile is fired.