- Home /
For some reason my zombies tries to go to 0 0 0 instead of the player and I don't know why
I made it in my script so that the zombies will know where the player is and go after them but for some reason it tries to go to 0 0 0 and I don't know why. Please take a look at the script and tell me what is wrong.
(Sorry if the code is bad I am a noob)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZK_Attacking : MonoBehaviour
{
public Transform Player;
public float MoveSpeed = 3.5f;
public float AttackRange = 1.0f;
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
Player = GameObject.Find("Player").transform;
}
void Update()
{
transform.LookAt(Player);
float dstSqr = (Player.position - transform.position).sqrMagnitude;
bool inAttackRange = (dstSqr <= AttackRange * AttackRange);
anim.SetBool("AttackingPlayer", inAttackRange);
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
}
}
Answer by AryaIsMe · May 03, 2021 at 08:58 PM
I fixed it by making it go towards the tag of the player instead of the player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZK_Attacking : MonoBehaviour
{
public Transform Player;
public float MoveSpeed = 3.5f;
public float InRadius = 1000.0f;
public float AttackRange = 1.0f;
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
Player = GameObject.FindGameObjectsWithTag("Player")[0].transform;
}
void Update()
{
Player = GameObject.FindGameObjectsWithTag("Player")[0].transform;
float dstSqr = (Player.position - transform.position).sqrMagnitude;
bool inRadius = (dstSqr <= InRadius * InRadius);
bool inAttackRange = (dstSqr <= AttackRange * AttackRange);
anim.SetBool("inRadius", inRadius);
anim.SetBool("AttackingPlayer", inAttackRange);
transform.position = Vector3.MoveTowards(transform.position, Player.position, MoveSpeed * Time.deltaTime);
}
}
Answer by Fariborzzn · May 01, 2021 at 09:42 AM
Hey @AryaIsMe, the reason why your zombie doesn't move to player is that you never asked him . simply replace your last line of code with this :
transform.position = Vector3.MoveTowards(transform.position, Player.position, MoveSpeed * Time.deltaTime);
let me know if your problem solved . best regards Fariborz
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Character Wont Stop Moving 1 Answer
Unity Build Showing Black Screen on Startup Using Oculus SDK 0 Answers