Convert all scripts to used tagged Player. Try to keep Shello on the ground while walking (not sure if this works yet). Fix transition from excitement to walking to happen immediately.
107 lines
3.0 KiB
C#
107 lines
3.0 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class ShelloController : MonoBehaviour
|
|
{
|
|
public LayerMask terainMask;
|
|
public float notice_distance;
|
|
|
|
// Angular speed in radians per sec.
|
|
public float rotationSpeed = 1.0f;
|
|
public float excitedDirection = 5;
|
|
|
|
Transform player;
|
|
Animator anim;
|
|
bool isAwake = false;
|
|
int awokenFrames = 0;
|
|
|
|
void Start()
|
|
{
|
|
anim = GetComponent<Animator>();
|
|
var players = GameObject.FindGameObjectsWithTag("Player");
|
|
if (players?.Length > 0)
|
|
{
|
|
player = players[0].transform;
|
|
}
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
if (player == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (isAwake)
|
|
{
|
|
return;
|
|
}
|
|
|
|
float dist = Vector3.Distance(player.position, transform.position);
|
|
var isExcited = dist < notice_distance;
|
|
|
|
if (!isExcited)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Determine which direction to rotate towards
|
|
Vector3 targetDirection = player.position - transform.position;
|
|
|
|
// The step size is equal to speed times frame time.
|
|
float singleStep = rotationSpeed * Time.deltaTime;
|
|
|
|
// Rotate the forward vector towards the target direction by one step
|
|
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);
|
|
|
|
// Draw a ray pointing at our target in
|
|
Debug.DrawRay(transform.position, newDirection, Color.red);
|
|
|
|
var rotateDiff = transform.forward.y - targetDirection.y;
|
|
|
|
// Calculate a rotation a step closer to the target and applies rotation to this object
|
|
transform.rotation = Quaternion.LookRotation(newDirection);
|
|
|
|
if (Mathf.Abs(rotateDiff) < excitedDirection)
|
|
{
|
|
anim.SetBool("isExcited", isExcited);
|
|
if (isExcited)
|
|
{
|
|
awokenFrames++;
|
|
if (awokenFrames > 60)
|
|
{
|
|
anim.SetBool("isWalking", true);
|
|
anim.SetBool("isExcited", false);
|
|
isAwake = true;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Debug.Log($"Rotation diff: {rotateDiff}");
|
|
}
|
|
}
|
|
|
|
void FixedUpdate()
|
|
{
|
|
Align();
|
|
}
|
|
|
|
private void Align()
|
|
{
|
|
RaycastHit hit;
|
|
var theRay = -transform.up;
|
|
|
|
if (Physics.Raycast(new Vector3(transform.position.x, transform.position.y, transform.position.z),
|
|
theRay, out hit, 20, terainMask))
|
|
{
|
|
Quaternion targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.parent.rotation;
|
|
|
|
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime / 0.15f);
|
|
transform.position = new Vector3(transform.position.x, transform.position.y - hit.distance, transform.position.z);
|
|
}
|
|
}
|
|
}
|