Untitled
unknown
csharp
3 years ago
2.4 kB
15
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIControl : MonoBehaviour
{
private Rigidbody rb;
public bool showGizmo;
[Space(10)]
public int countOfRays = 3;
public float distaneOfRay = 3;
private float angle = 90;
[Header("Abilities")]
public float turnSpeed = 1;
public float walkSpeed = 1;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
Sensors();
}
private void FixedUpdate()
{
Move();
}
void Sensors()
{
Vector3 deltaPosition = Vector3.zero;
for (int i = 0; i < countOfRays; i++)
{
Quaternion rotation = this.transform.rotation;
Quaternion rotationMod = Quaternion.AngleAxis(i / ((float)countOfRays - 1) * angle * 2 - angle, this.transform.up);
Vector3 direction = rotation * rotationMod * Vector3.forward;
Ray ray = new Ray(this.transform.position + new Vector3(0,1,0), direction);
RaycastHit hitInfo;
if(Physics.Raycast(ray, out hitInfo, distaneOfRay))
{
deltaPosition -= (1.0f / countOfRays) * turnSpeed * direction;
}
else
{
deltaPosition += (1.0f / countOfRays) * turnSpeed * direction;
}
}
//this.transform.position += deltaPosition * Time.deltaTime;
Vector3 turningDirection = Vector3.RotateTowards(transform.forward, deltaPosition, turnSpeed * Time.deltaTime, 0);
transform.rotation = Quaternion.LookRotation(turningDirection);
}
void Move()
{
rb.velocity = transform.forward * walkSpeed;
}
private void OnDrawGizmos()
{
if(showGizmo)
{
for (int i = 0; i < countOfRays; i++)
{
Quaternion rotation = this.transform.rotation;
Quaternion rotationMod = Quaternion.AngleAxis(i / ((float)countOfRays - 1) * angle * 2 - angle, this.transform.up);
Vector3 direction = rotation * rotationMod * Vector3.forward;
Gizmos.color = Color.yellow;
Gizmos.DrawRay(this.transform.position + new Vector3(0, 1, 0), direction * distaneOfRay);
}
}
}
}Editor is loading...