I made a script for butterfly flying in random direction that is presented by randomly generated vector3.
But i dont seem to be able to make it face the direction its flying(
Any help would be appritiated.
using UnityEngine;
using System.Collections;
public class Butterfly : MonoBehaviour
{
public float TimeMin = 0.5f;
public float TimeMax = 2f;
public float MinSpeed = 3;
public float MaxSpeed = 6;
public float MinX = -3;
public float MinY = -3;
public float MinZ = -3;
public float MaxX = 3;
public float MaxY = 3;
public float MaxZ = 3;
public float strength = 0.5f;
public float AnimationSpeed = 1;
public Vector3 Offset = new Vector3 (0, -0.5f, 0);
public LayerMask HitLayers;
private float ToGround;
private float Tick;
private Vector3 MoveTo;
private float Timer;
private Quaternion targetRotation;
//private Animator Anim;
void Awake ()
{
//Anim = GetComponent<Animator>();
Timer = Random.Range(TimeMin, TimeMax);
MoveTo = new Vector3
(Random.Range(MinX,MaxX),
Random.Range(MinY, MaxY),
Random.Range(MinZ, MaxZ));
}
void FixedUpdate ()
{
RaycastHit Hitinfo;
Ray ray = new Ray(transform.position,Vector3.down);
Physics.Raycast(ray, out Hitinfo, 30, HitLayers);
Debug.DrawRay(transform.position + Offset, Vector3.down * 30, Color.red);
ToGround = Hitinfo.distance;
if (ToGround < 3)
MoveTo += new Vector3(0, 1, 0);
if (ToGround > 10)
MoveTo -= new Vector3(0, 1, 0);
transform.Translate(MoveTo * Time.deltaTime, transform);
targetRotation = Quaternion.LookRotation(MoveTo - transform.position);
var str = Mathf.Min(strength * Time.deltaTime, 1);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, str);
Tick += Time.deltaTime;
if (Tick > Timer)
{
MoveTo = new Vector3
(Random.Range(MinX, MaxX),
Random.Range(MinY, MaxY),
Random.Range(MinZ, MaxZ));
Tick = 0;
}
}
try
Vector3 lookDirection = (MoveTo - transform.position).normalized;
targetRotation = Quaternion.LookRotation(lookDirection);