As part of my newly started education in gamedevelopment I encoutered a peculiar issue: we have each progammed an NPC so when the player came within a certain distance of the NPC, the NPC would react by moving towards the player. However, in my project, the NPC “moonwalks” away from the player, a development which have left my teacher stumped.
Here is the code in question, the programming language is C#:
using UnityEngine;
using System.Collections;
public class Troll : MonoBehaviour {
Animation anim;
GameObject player;
// Use this for initialization
void Start () {
anim = GetComponent<Animation> ();
anim.Play ("Idle_02");
player = GameObject.FindGameObjectWithTag ("Player");
}
// Update is called once per frame
void Update (){
if (Vector3.Distance (transform.position, player.transform.position) < 3) {
Vector3 dir = new Vector3 (player.transform.position.x, transform.position.y, player.transform.position.z);
transform.LookAt (dir);
anim.Play ("Attack_01");
rigidbody.velocity = new Vector3 (0, rigidbody.velocity.y, 0);
} else if (Vector3.Distance (transform.position, player.transform.position) < 20) {
Vector3 dir = new Vector3 (player.transform.position.x, transform.position.y, player.transform.position.z);
transform.LookAt (dir);
anim.Play ("Run");
rigidbody.AddForce (transform.forward * 100);
} else {
anim.Play ("Idle_01");
}
}
}
An odd detail is that if I change “rigidbody.AddForce (transform.forward * 100);” to a negative number, the NPC will move forward.
The NPC is the “Earthborn Troll” from the asset store, in case that is an important detail.
I would greatly appreciate any help.