Question by
Cinhil124a · Apr 10, 2020 at 09:06 PM ·
rigidbodyraycastquaternion
Enemy Rotating on wrong axis after Raycasting
Working with bits of code from BurgZerg, it was tracking my player properly and rotating properly, added in the raycast section now and it rotates on the X axis when it never did that before and constraints are all locked, only started once i added in the new raycast section to this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovementA : MonoBehaviour
{
Vector3 raycastOffset = Vector3.zero;
GameObject player;
Transform target;
public float movementSpeed = 10f;
public float rotationalDamp = .5f;
public float rayCastOffset = 2.5f;
public float detectionDistance = 20f;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
target = player.transform;
}
void Update()
{
PathFinding();
// Turn();
Move();
}
void Turn()
{
Vector3 pos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(pos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationalDamp * Time.deltaTime);
}
void Move()
{
transform.position += transform.forward * movementSpeed * Time.deltaTime;
}
void PathFinding()
{
RaycastHit hit;
Vector3 left = transform.position - transform.right * rayCastOffset;
Vector3 right = transform.position + transform.right * rayCastOffset;
// Vector3 up = transform.position + transform.up * rayCastOffset;
// Vector3 down = transform.position - transform.up * rayCastOffset;
Debug.DrawRay(left, transform.forward * detectionDistance, Color.cyan);
Debug.DrawRay(right, transform.forward * detectionDistance, Color.cyan);
// Debug.DrawRay(up, transform.forward * detectionDistance, Color.cyan);
// Debug.DrawRay(down, transform.forward * detectionDistance, Color.cyan);
if (Physics.Raycast(left, transform.forward, out hit, detectionDistance))
{
raycastOffset += Vector3.right;
}
else if (Physics.Raycast(right, transform.forward, out hit, detectionDistance))
{
raycastOffset -= Vector3.right;
}
/* not used in my code, great for up and down movement changes
if (Physics.Raycast(up, transform.forward, out hit, detectionDistance))
raycastOffset -= Vector3.up;
if (Physics.Raycast(down, transform.forward, out hit, detectionDistance))
raycastOffset += Vector3.up;
*/
if (raycastOffset != Vector3.zero)
{
transform.Rotate(raycastOffset * 5f * Time.deltaTime);
}
else
Turn();
}
}
Comment