So, my boss moves in a specific direction when it detects the player. The problem I'm having is how to get the boss to move depending on where the player is within a certain proximity. So if the boss is on the player's left, he'll move to the left. If he's on the player's right, he'll move to the right. But I can't figure out how to make him react based on distance. Right now I'm just doing a Debug.Log to save a few seconds.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class phantom : MonoBehaviour {
private Rigidbody2D rb;
private Animator anim;
public Transform Target;
void Start ()
{
rb = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
}
void Update ()
{
if (transform.position.x > Target.position.x ) {
Debug.Log ("left");
}
if (transform.position.x < Target.position.x ) {
Debug.Log ("right");
}
}
}
You could use the Vector3.Distance method to determine the distance between your two object based on thier respective transform. That way, you can modify your boss's behavior according to his proximity to the player. The smaller the magnitude value is, the closer your two transforms are.
Ex:
int distanceYouWant;
if(Vector3.Distance(transform.position, Target.position).magnitude < distanceToDoStuff)
{
Debug.Log("Boss do stuff!");
}
Here is the link to the Unity scripting API doc: https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
Hope this helps!
I figured it out. I just made the function not in Update but with an OnTriggerEnterStay2d (Collider2D other). Then I placed a trigger collider on the same GameObject and only when it detects the Target (the player) does the debug come up.
Related
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveProjectile : MonoBehaviour
{
public Rigidbody2D projectile;
public float moveSpeed = 10.0f;
// Start is called before the first frame update
void Start()
{
projectile = this.gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
projectile.velocity = new Vector2(0,1) * moveSpeed;
}
void OnCollisionEnter2D(Collision2D col){
if(col.gameObject.name == "Enemy"){
gameObject.name == "EnemyHeart5".SetActive(false);
}
if(col.gameObject.name == "Top"){
DestroyObject (this.gameObject);
}
}
}
This is the code to my player projectile. On collision i tried to reference it to a game object i have called playerheart and it doesnt seem to work out the way i wanted it to.
Im trying to make a health system where if my bullet collides with the enemy game object the health would decrease by one. Im pretty new to Unity and im confused on how to target the hearts when the bullets collide.
I'm assuming "EnemyHeart5" is a GameObject inside Enemy as child gameobject. Correct?
Issue here is when the collision takes place, it recognize "Enemy" gameobject and won't have access to "EnemyHeart5" for disabling it. I'd suggest you to add simple EnemyManager script into your enemy which manages your enemy health and health related gameobject (ie. EnemyHearts which you are displaying). When collision takes place, access that EnemyManager component and change health value.
void OnCollisionEnter2D(Collision2D col){
if(col.gameObject.tag == "Enemy"){
col.gameObject.GetComponent<EnemyManager>().health =-1;
}
Now, in the update method of EnemyManager you check the health value and disable EnemyHealth5 component.
Also, use "tag" in collision instead of "name". name will create issues when you have multiple enemies in the game. Make sure you add tag in enemy gameobject if you are using it.
Hope this helps, let me know how it goes.
I am trying to make a zombie wave game and current have a Prefab for my enemies. If I have the prefab be in the scene when I hit run, they are attached to the NavMesh and track the player perfectly. I want to achieve this but with the enemy being spawned from an empty GameObject so I can get the waves spawning in. I have achieved them Spawning but they have the error,
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)
EnemyAI:Update() (at Assets/Scripts/EnemyAI.cs:25)
Here is my EnemyAI Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
public float lookRadius = 10f;
Transform target;
NavMeshAgent agent;
public GameObject Player;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(Player.transform.position, transform.position);
if (distance <= lookRadius)
{
agent.SetDestination(Player.transform.position);
}
}
}
And my spawning script, which is attached to an empty game object,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawning : MonoBehaviour
{
public GameObject prefab;
public int CountofCubes;
private IEnumerator coroutine;
public float spawnRate;
IEnumerator Start()
{
while (true)
{
for (int i = 0; i < CountofCubes; i++)
{
Instantiate(prefab, new Vector3(Random.Range(-25.0f, 25.0f), 0.5f, Random.Range(-25.0f, 25.0f)), Quaternion.identity);
}
yield return new WaitForSeconds(spawnRate);
}
}
}
Any help would be great thanks!
I had the same issue and I don't have an explanation but only a workaround:
In the Start fucntion, I added:
navAgent = GetComponent<NavMeshAgent>();
navAgent.enabled = false;
// Invoke is used as a workaround for enabling NavMeshAgent on NavMeshSurface
Invoke("EnableNavMeshAgent", 0.025f);
And the EnableNavMeshAgent function is just :
private void EnableNavMeshAgent ()
{
navAgent.enabled = true;
}
If I set the invoke delay to a value less than 0.025 second the error keep going but for 0.025 I only have it twice and the behaviour is the one I wanted after that.
Some reasons this might happen:
The agent is not on level with any navmesh i.e. can be too far above or below. You want it to be "close to the NavMesh surface". Use raycasting on the floor to position the agent or add a rigidbody and drop it from above the floor. After you do this you might need to disable and enable the agent.
Moving the transform yourself rather than using Wrap function. There's property where you can check if the simulated and actual position are in sync.
Corrupted navmesh so you might need to re-bake it.
It is essentially trying to tell you your agent is not on the mesh so it cannot find a path. Try playing with where you're placing the agent.
I kind of remember running into a similar problem a while back and problem was I forgot to bake the NavMesh in Window > AI > Navigation. Just in case.
I am trying to make a basic platformer using Unity and my player has a sort of gun. My bullet is only shooting in one location, and I would like it to rotate with the player. I am quite new to C# and need some help.
I have tried using if and else statements and I have tried manually rotating it.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fire : MonoBehaviour
{
public Transform player;
public Rigidbody2D rb2d;
public Transform enemy;
public Transform myspawn;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Spawn"))
{
transform.position = player.position;
rb2d.velocity = new Vector2(10.0f, 0.0f);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.transform == enemy)
{
transform.position = myspawn.position;
}
}
}
I expect the output to rotate the bullet with the player, and using the if statements I got a lot of different errors. The actual output I got was the bullet just wouldn't move until you manually push the bullet.
If your gun is only shooting at one direction you can do something like this:
Create a new boolean variable, call it something like isLookingRight in your player controller script and set it to true if your player is initially looking at right. Whenever player moves left, change this variable to false and change your Update in the code you have provided to this:
void Update()
{
if (Input.GetButtonDown("Spawn"))
{
transform.position = player.position;
if(playerScript.isLookingRight){
rb2d.velocity = new Vector2(10.0f, 0.0f);
}
else{
rb2d.velocity = new Vector2(-10.0f, 0.0f);
}
}
What this code does is pretty simple, if your player is looking left, it just changes the velocity to the opposite of what it would normally be. But you need to be changing the isLookingRight correctly in your player movement script.
I am in the middle of working on a game, and I just started. I added in the map as a png and have been adding in colliders around the areas that I want to be impassable (it is a 2D platformer). I have an enemy already designed and added a 2DRigidBody component to it as it moves around, and started to use 2DBoxColliders as the colliders for the level, and my script that I have written:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sexapus : MonoBehaviour {
public static int Velocity = 42;
public Rigidbody2D rb;
public Vector2 dir;
public Animator anim;
void Start () {
rb = GetComponent<Rigidbody2D>();
dir = new Vector2(1, 0);
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
rb.velocity = dir * Velocity;
anim.SetFloat ("Direction", dir.x);
}
void OnCollisionEnter2D (Collision2D col) {
dir = dir * -1;
}
//CHECK TASKS
}
Meant that the enemy would hit the side of a wall and then rotate and start going the other way. I realised with the size of my map that using multiple 2DBoxColliders (and when I say multiple I mean I would probably have to use over a hundred) was a very bad way of doing it. I have now started to use a 2DpolygonCollider for the map as well, but now the enemy doesn't collide with the sides of the wall and turn around, it just stays facing the same direction but doesn't move. Anyone know why?
You are using the same collider for the floor and the walls... So when you collide with the wall, and are already touching the floor, the OnCollisionEnter will not happen.
So, you do get the collision, hence the object cant move past the wall, BUT it's not a new collision!
Solution: Use a collider to the floor, and a different one to the walls, Edge colliders are good for this.
The script below is attached to the enemy on my game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour {
private Animator attack;
Transform player;
UnityEngine.AI.NavMeshAgent nav;
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
nav = GetComponent<UnityEngine.AI.NavMeshAgent> ();
}
The code just below is getting the enemy to stop at a certain distance and shoot from the trigger "Attack". (Below and above are all the same code).
// Update is called once per frame
void Update () {
nav.SetDestination(player.position);
float distance = Vector3.Distance(this.transform.position, player.position);
if (distance < 10f)
{
Animator an = GetComponent<Animator>();
an.SetTrigger("Attack");
}
Debug.Log("distance" + distance);
}
}
This script basically uses the Nav Agent to make the enemy go towards my player and to start a shoot animation when the enemy is at a certain range.
Any help would be great. Thank you.
You should use a boolean for the check instead of a Trigger. You should change your code to set the boolean Attacking to false when the player is not in range and set the boolean to true when the player is in range for attacking. Also, make sure your animation clip loop is ticked on.