MayHeCome/Assets/Scripts/Battle/ArrowBehaviour.cs
2024-12-18 17:55:34 +08:00

52 lines
1.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrowBehaviour : MonoBehaviour
{
// From: https://gamedev.stackexchange.com/questions/183507/add-parabola-curve-to-straight-movetowards-movement
public float speed = 100;
public Vector3 target;
public float arcHeight = 2;
Vector3 _startPosition;
float _stepScale;
float _progress;
void Start() {
_startPosition = transform.position;
float distance = Vector3.Distance(_startPosition, target);
// This is one divided by the total flight duration, to help convert it to 0-1 progress.
_stepScale = speed / distance;
}
void Update() {
// Increment our progress from 0 at the start, to 1 when we arrive.
_progress = Mathf.Min(_progress + Time.deltaTime * _stepScale, 1.0f);
// Turn this 0-1 value into a parabola that goes from 0 to 1, then back to 0.
float parabola = 1.0f - 4.0f * (_progress - 0.5f) * (_progress - 0.5f);
// Travel in a straight line from our start position to the target.
Vector3 nextPos = Vector3.Lerp(_startPosition, target, _progress);
// Then add a vertical arc in excess of this.
nextPos.y += parabola * arcHeight;
// Continue as before.
transform.LookAt(nextPos, Vector3.forward);
transform.position = nextPos;
// I presume you disable/destroy the arrow in Arrived so it doesn't keep arriving.
if(_progress >= 1.0f)
Arrived();
}
void Arrived()
{
Destroy(this.gameObject);
}
}