Skip to content

Instantly share code, notes, and snippets.

@RaheelYawar
Last active March 17, 2024 21:11
Show Gist options
  • Save RaheelYawar/6457daf45691f93a90c70e7de3a2363c to your computer and use it in GitHub Desktop.
Save RaheelYawar/6457daf45691f93a90c70e7de3a2363c to your computer and use it in GitHub Desktop.
Guided Missile - positional update routine for a guided missile that tracks a player
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
[SerializeField] private GameObject target = null;
private const float TURN_RATE = 0.5f;
private const float CONTACT_DISTANCE = 1; // explode at distance
private const float LOCK_DISTANCE = 2; // stop chasing and lock on last position
private const float ACCELERATION = 0.01f;
private const float LAUNCH_VELOCITY = 0.01f;
private const float MAX_VELOCITY = 2;
private Vector3 _directionVector;
private Vector3 _lockPosition;
private float _currentVelocity = 0;
void Start()
{
_launch();
}
private void _launch()
{
_lockPosition = target.transform.position;
_updateDirectionVector(transform.position, _lockPosition);
_currentVelocity = LAUNCH_VELOCITY;
}
void FixedUpdate()
{
// If the projectile is not locked on keep chasing the target
if (Vector3.Distance(transform.position, _lockPosition) > LOCK_DISTANCE)
{
_lockPosition = target.transform.position;
_updateDirectionVector(transform.position, _lockPosition);
transform.rotation = Quaternion.LookRotation(_directionVector); // look where its going
}
// Move based on direction vector
transform.position += _directionVector * (Time.deltaTime * _currentVelocity);
_currentVelocity += ACCELERATION * Time.deltaTime;
_currentVelocity = Math.Max(_currentVelocity, MAX_VELOCITY);
// Explode when in range
if (isColliding() || Vector3.Distance(transform.position, _lockPosition) < CONTACT_DISTANCE)
{
this.gameObject.SetActive(false);
if (Vector3.Distance(target.transform.position, transform.position) < CONTACT_DISTANCE)
{
// TODO: damage based on the distance
damageTarget();
}
// TODO: play FX and SFX
// TODO: add projectile back into projectile pool
}
}
/// <summary>
/// Update the direction vector based on player movement.
/// </summary>
private void _updateDirectionVector(Vector3 startPosition, Vector3 endPosition)
{
var newDirection = endPosition - startPosition;
_directionVector = Vector3.Lerp(_directionVector, newDirection, Time.deltaTime * TURN_RATE);
_directionVector.Normalize();
}
private bool isColliding()
{
}
private void damageTarget()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment