gpt4 book ai didi

c# - 如何从玩家位置设置随机目标

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:51 25 4
gpt4 key购买 nike

我是 Unity 的新手。在我的项目中,我在玩家位置实例化了一个球。从球员位置开始,球应该转到 40 到 90 度的随机位置。如果玩家处于 0,0,0 位置。目标应该是 10,0,0。

我已经完成了代码。但它并不完美。我做错了什么。它应该随机设置目标。

public class Movetowards3: MonoBehaviour {

// Use this for initialization
GameObject go;
public GameObject prefab;
public GameObject Target;
public GameObject endPos1;
public Vector3 endpos2;
float speed = 5f;
public bool s=false;
public GameObject player;
public bool s2=false;

void Start () {
go = Instantiate(prefab, player.transform.localPosition, Quaternion.identity);
}

// Update is called once per frame
void Update () {
player=GameObject.FindGameObjectWithTag("Player");

if(s==true)
{

go = Instantiate(prefab, player.transform.localPosition, Quaternion.identity);
endpos2 =new Vector3(player.transform.position.x+10f,player.transform.position.y,player.transform.position.z);
s=false;
}

if(go.transform.position != endpos2)
{
Vector3 newPos = Vector3.MoveTowards(go.transform.localPosition, endpos2,speed * Time.deltaTime);
go.transform.position = newPos;
}
}
}

我增加了 x 的值,但我认为它不正确。

最佳答案

从本质上讲,您的代码是正确的,但问题是 endpos 没有机会实例化。

我认为这是你的问题:

这里:

public bool s=false;

您将 s 设置为 false,以后再也不会更改它。这成为一个问题:

if(s==true)
{

go = Instantiate(prefab, player.transform.localPosition, Quaternion.identity);
endpos2 =new Vector3(player.transform.position.x+10f,player.transform.position.y,player.transform.position.z);
s=false;
}

并且,您需要这些实例化以开始您在下一个 if 语句中执行的操作:

   if(go.transform.position != endpos2)
{
Vector3 newPos = Vector3.MoveTowards(go.transform.localPosition, endpos2,speed * Time.deltaTime);
go.transform.position = newPos;
}

所以我建议您要么使 public bool s=true;

或者在第一个 if 语句中添加 else 语句。

也只是旁注,你实例化了两次,我不知道那是不是故意的,但他们在做同样的事情。

关于c# - 如何从玩家位置设置随机目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49209936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com