So i know how to make things attack me and come after me, easy. But how would i go about making something like an animal that runs away a if you go close to it (and only run a few meters not forever) any suggestions?
Without spending too much time on it, here is a simple example of how you might do this. Check the Update function in the Animal script for the meat of the action.
-
In an empty scene, create two cubes.
-
Give the first cube the tag “Player”. Create a new C# script called Player, copy the code below into that script, and attach the Player script to the first cube.
using UnityEngine;
using System.Collections;public class Player : MonoBehaviour {
private Transform thisTransform; public float runSpeed = 20; void Awake() { thisTransform = transform; thisTransform.position = new Vector3(0, 0, 0); } public Transform GetTransform() { return thisTransform; } void Update() { float keyboardX = Input.GetAxis("Horizontal"); float keyboardY = Input.GetAxis("Vertical"); var newPos = thisTransform.position + new Vector3(keyboardX, 0, keyboardY); thisTransform.position = Vector3.MoveTowards(thisTransform.position, newPos, Time.deltaTime * runSpeed); }}
-
Create a new C# script called Animal, copy the code below into that script, and attach the Animal script to the second cube.
using UnityEngine;
using System.Collections;public class Animal : MonoBehaviour {
Player player; Transform thisTransform; public float minDistance = 10; public float runSpeed = 10; void Awake() { thisTransform = transform; thisTransform.position = new Vector3(2, 0, 2); } void Start() { player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); } void Update() { if(Vector3.Distance(player.GetTransform().position, thisTransform.position) < minDistance) { Vector3 direction = thisTransform.position - player.GetTransform ().position; direction.Normalize(); thisTransform.position = Vector3.MoveTowards(thisTransform.position, direction * minDistance, Time.deltaTime * runSpeed); } }}
-
Press play and chase the cube around!