GameObject跟随光标还跟随敌人?

时间:2018-04-24 08:12:17

标签: unity3d

我制作了一个跟随玩家光标的简单角色。我还想要的是当游戏对象"敌人"然后出现角色然后前往该位置以提醒玩家。一旦敌人离开,角色就像正常一样继续跟随光标。有没有理由说我的剧本不能奏效。我怎么能解释它?

public class FollowCursor : MonoBehaviour 
{   
    void Update () 
    {
        //transform.position = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
        if (gameObject.FindWithTag == "Enemy") 
        {           
            GameObject.FindWithTag("Enemy").transform.position
        }
        if (gameObject.FindWithTag != "Enemy")
        {       
            transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您没有正确使用FindWithTag,因为这是一个将字符串作为参数的方法,您需要像这样使用它: Unity scripting API

中所述的GameObject.FindwithTag("Something")

现在要将此应用于您的代码,您需要执行以下操作,根据是否找到敌人来设置您的玩家位置(假设此脚本位于您的实际玩家对象上):

if(GameObject.FindWithTag("Enemy"))
{
    //If an enemy is found with the tag "Enemy", set the position of the object this script is attatched to to be the same as that of the found GameObject.
    transform.position = GameObject.FindWithTag("Enemy").transform.position;
}
else
{
    //when no enemy with the tag "Enemy" is found, set this GameObject its position to the the same as that of the cursor
    transform.position = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
}

但是,此代码只会将您的播放器立即捕捉到找到的敌人的位置。如果这不是您想要的行为,您可以使用Vector3.MoveTowards之类的功能来让玩家逐渐移动它。

此代码还有优化空间,因为每个更新帧搜索GameObject都不是理想的解决方案。但是现在它应该有效。

答案 1 :(得分:-1)

我要为你编写所有函数的代码,我不太确定你的代码的beavihour,我知道游戏对象会附加到鼠标位置,所以不是真的跟着...... / p>

Vector3 targetPosition;
public float step = 0.01f;
void Update()
{

//if there is any enemy "near"/close
//targetPosition = enemy.position; 
//else
//targetPosition = MouseInput;

transform.position = Vector3.MoveTowards(transform.position, targetPosition , step);
}

对于f你可以使用SphereCast并从返回的敌人那里获得最接近的敌人。

相关问题