using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyControler : MonoBehaviour
{
private Transform player;
// Start is called before the first frame update
void Start()
{
//Note in this case we're saving the transform in a variable to work with later.
//We could save the player's game object (and just remove .transform from the below) but this is cleaner
var player = GameObject.FindWithTag("Player").transform;
}
// Update is called once per frame
void Update()
{
//**** The code below you need to modify and move into your own method and call that method from here.
//**** Don't overthink it. Look at how Start() is defined. Your own Move method would look the exact same.
//**** Experiment making it private void instead of public void. It should work the same.
//How much will we move by after 1 second? .5 meter
var step = .5f * Time.deltaTime; // 5 m/s
var newPosition = Vector3.MoveTowards(transform.position, player, step);//This is one way to move a game object by updating the transform. Watch the videos in this module and it should become apparent what goes here.
}
}
轉換不會映射到標記的玩家。我試圖讓一個敵人團結起來向一個移動的玩家移動一個班級,但我完全迷失了。
uj5u.com熱心網友回復:
您的代碼中有三個問題。首先是您player
在 Start 方法中定義了一個新變數。這隱藏了player
您之前定義的成員欄位。
第二個問題是您獲得了一個要移動的值,但您沒有將該值分配給當前物件位置。
第三個問題是你在Transform
方法中輸入了a MoveTowards
,而你本應該輸入 a Vector2
。
下面的代碼應該可以糾正這些問題。
public class EnemyControler : MonoBehaviour
{
private Transform _player;
void Start()
{
_player = GameObject.FindWithTag("Player").transform;
}
void Update()
{
var step = .5f * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, _player.position, step);
}
}
uj5u.com熱心網友回復:
嘗試做類似的事情,一旦您了解代碼,將其更改為您想要的,我過去曾使用過類似的事情
public int minRange;
private Transform target = null;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
target = other.transform;
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
target = null;
}
void update()
{
transform.LookAt(target);
float distance = Vector3.Distance(transform.position,
target.position);
bool tooClose = distance < minRange;
Vector3 direction = tooClose ? Vector3.back : Vector3.forward;
if (direction == Vector3.forward)
{
transform.Translate(direction * 6 * Time.deltaTime);
}
else
{
transform.Translate(direction * 3 * Time.deltaTime);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/511524.html
標籤:C#unity3d
下一篇:成員變數只維護函式范圍的賦值