Dopiero zaczynam zabawę z silnikiem Unity - nigdy nie programowałem. Mam pytanie - co zrobić, żeby NPC podążał za Playerem, gdy ten wejdzie w promień "Player Check"?
Poniżej kod dodany do NPC:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC_1 : MonoBehaviour
{
public float moveSpeed;
private Rigidbody2D myRigidbody;
public bool isWalking;
public float walkTime;
private float walkCounter;
public float waitTime;
private float waitCounter;
private int WalkDirection;
public Transform PlayerCheck;
public float PlayerCheckRadius;
private bool playerFind;
public Transform AtackCheck;
public float AtackCheckRadius;
public LayerMask WhatIsPlayer;
private bool atack;
private bool grouned;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask WhatIsGround;
private Animator anim;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
myRigidbody = GetComponent<Rigidbody2D>();
waitCounter = waitTime;
walkCounter = walkTime;
}
private void FixedUpdate()
{
atack = Physics2D.OverlapCircle(AtackCheck.position, AtackCheckRadius, WhatIsPlayer);
grouned = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, WhatIsGround);
playerFind = Physics2D.OverlapCircle(PlayerCheck.position, PlayerCheckRadius, WhatIsPlayer);
}
// Update is called once per frame
void Update()
{
if (playerFind)
{
}
if (atack)
{
anim.SetBool("Atack", atack);
}
if (grouned)
{
switch (WalkDirection)
{
case 0:
myRigidbody.velocity = new Vector2(-moveSpeed, 0);
break;
case 1:
myRigidbody.velocity = new Vector2(0, moveSpeed);
break;
case 2:
myRigidbody.velocity = new Vector2(moveSpeed, 0);
break;
case 3:
myRigidbody.velocity = new Vector2(0, -moveSpeed);
break;
}
}
if (isWalking)
{
walkCounter -= Time.deltaTime;
if(walkCounter <0)
{
isWalking = false;
waitCounter = waitTime;
}
switch(WalkDirection)
{
case 0:
myRigidbody.velocity = new Vector2(-moveSpeed, 0);
break;
case 1:
myRigidbody.velocity = new Vector2(0, moveSpeed);
break;
case 2:
myRigidbody.velocity = new Vector2(moveSpeed, 0);
break;
case 3:
myRigidbody.velocity = new Vector2(0, -moveSpeed);
break;
}
}
else
{
waitCounter -= Time.deltaTime;
myRigidbody.velocity = Vector2.zero;
if(waitCounter <0)
{
ChooseDirection();
}
}
}
public void ChooseDirection()
{
WalkDirection = Random.Range (0, 4);
isWalking = true;
walkCounter = walkTime;
Random.Range(10, 170);
}
}