What is the best way to make moving obstacles in a 3d game?
I am on ep 10 of Brackeys "How to make a game" series (an obstacle dodging game) and he made different levels by just duplicating his original one and removing obstacles in it. He said that this is for test purposes and that we can make our own levels. So, I decided to make a level where there are moving obstacles. I was having a lot of trouble with making moving obstacles so I need your help. Should I add a moving obstacle prefab and the code in a gamemanager?
All that im trying to say is that i need a script for moving obstacles and where to put that script. Help would be greatly appreciated. Thank you!
There are several ways to do this. I like having the obstacles on a navmesh and have them move to random locations upon entering their destination. You could put a randomizing script on the waypoints (below). first, you need a nav$$anonymous$$esh in the scene, then a nav$$anonymous$$eshAgent on the obstacles, then targets for them to navigate towards with the below script and a trigger collider. When they arrive at their target, they get instructions to go to another target. You need this script on the targets. This script is set up to randomize where the obstacles go. It is set up for 4 different targets. you would drag the other targets into the variable slot. OTHER targets! meaning target 1 would have targets 2,3, and 4. Target 2 would have targets 1,3,and 4. I tested it and it works. Tag the obstacle "obstacle". eventually turn off the meshrendereer for the waypoints so you don't see them
using UnityEngine;
using System.Collections;
public class test$$anonymous$$ove : $$anonymous$$onoBehaviour {
public float speed = 3;
public GameObject[] targets;//possible waypoints for target to go to
Nav$$anonymous$$eshAgent agent;
public GameObject nextTarget = null;//actual waypoint the obstacle will go to. Leave this blank
void Start () {
}
void OnTriggerEnter(Collider other) {
if(other.CompareTag ("obstacle")){//your obstacle
agent= other.gameObject.GetComponent<Nav$$anonymous$$eshAgent>();//gets the navmesh of the obstacle entering the waypoint
nextTarget = targets [Random.Range (0, targets.Length)];//sets the next waypoint from the list
agent.SetDestination(nextTarget.transform.position);//tells obstacle to go to tnextTarget
}
}
void OnTriggerExit(Collider other) {
if(other.CompareTag ("obstacle")){
nextTarget=null;//resets the target for next obstacle when this obstacle leaves on his way to next waypoint
}
}
}
Your answer
Follow this Question
Related Questions
Stop movement on collision 1 Answer
OPC UA Client & Server SDK for .NET not working on Unity from www.traeger.de 0 Answers
Literally No Scripts are loading 1 Answer
grab multiple object 0 Answers