- Home /
AI Character not rotating when spawned in
To give you some background, I have a button which spawns a prefab wherever I click/touch afterward to place it down. After that, I have a simple wandering script that changes direction every 3 seconds and travels forward using it's character controller.
The problem, however, is that if I drag the prefab into the editor and press play, the little fella moves fine, but if I use the button to spawn it in-game, it will only move forward, never turning. This is the script I use:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class Wander : MonoBehaviour {
public float velocityMax;
private float x;
private float z;
private float time;
private float angle;
public bool isTouchWall;
// Use this for initialization
void Start () {
x = Random.Range(-velocityMax, velocityMax);
z = Random.Range(-velocityMax, velocityMax);
angle = Mathf.Atan2(x, z) * (180 / 3.141592f) + 90;
transform.rotation = Quaternion.Euler( 0, angle, 0);
animation.wrapMode = WrapMode.Loop;
animation.Play("walk");
isTouchWall = false;
}
void OnCollisionStay(Collision collisionInfo) {
foreach (ContactPoint contact in collisionInfo.contacts) {
if (contact.otherCollider.gameObject.tag.Equals("Barrier")) {
isTouchWall = true;
}
}
}
// Update is called once per frame
void Update () {
if (Time.timeScale >= 1) {
time += Time.deltaTime;
if (time > 3.0f) {
x = Random.Range(-velocityMax, velocityMax);
z = Random.Range(-velocityMax, velocityMax);
angle = Mathf.Atan2(x, z) * (180 / 3.141592f) + 90;
if (isTouchWall == true) {
if (angle + 180 < 360)
angle += 180;
else
angle -= 180;
isTouchWall = false;
}
transform.rotation = Quaternion.Euler(0, angle, 0);
time = 0.0f;
Debug.Log("turn");
}
Vector3 forward = transform.TransformDirection(Vector3.forward);
gameObject.GetComponent<CharacterController>().SimpleMove(forward * velocityMax);
}
}
}
The angle is only changing when it touches a wall. Is that on purpose?
No it changes right before that with angle = $$anonymous$$athf.Atan2(x, z) * (180 / 3.141592f) + 90;
$$anonymous$$aybe it isn't rotating because Time.timeScale >= 1
is not true. would that be the problem? I really cant think of anything else
Nah, it does everything else in the method except rotate. And like I said in the initial post, it acts completely normal if I place it into the world by just dragging it in. It's only if I instantiate it that it doesn't turn. It still moves forward and prints the debug log.
Your answer
![](https://koobas.hobune.stream/wayback/20220613100617im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to change the angle my character falls at 1 Answer
Player model rotates forward with camera 0 Answers
How can I get my model to face the direction it is moving? 2 Answers
[2D] CharacterController rotation 0 Answers
Face direction to move in 2 Answers