In my game you can slice things in half, but I want to make sure the player is actually moving his sword fast in order to slice things.
speed = Vector3.Distance(transform.position, lastPos) / Time.deltaTime;
lastPos = transform.position;
This code works for getting the speed of the sword, but only if the player is standing still, the moment the player starts moving with the sword the speed jumps up to over 500. Why does that happen?
Full code
using UnityEngine;
public class SliceListener : MonoBehaviour
{
public Slicer slicer;
private float speed;
private Vector3 lastPos;
private void Start()
{
lastPos = transform.position;
}
private void OnTriggerEnter(Collider other)
{
Explosive explosive = other.GetComponent<Explosive>();
if ( explosive && speed > 2 / Time.timeScale)
{
explosive.Explode();
return;
}
if ( speed < 4 / Time.timeScale && !other.CompareTag("Bullet") )
{
return;
}
slicer.isTouched = true;
Enemy enemy = other.GetComponent<Enemy>();
if ( enemy )
{
Destroy(enemy);
Destroy(enemy.GetComponentInChildren<AudioSource>());
}
Turret turret = other.GetComponent<Turret>();
if ( turret )
{
Destroy(turret);
Destroy(turret.GetComponentInChildren<AudioSource>());
}
}
private void Update()
{
speed = Vector3.Distance(transform.position, lastPos) / Time.deltaTime;
lastPos = transform.position;
}
}