[英]Making an object move in a random direction in Unity
I have an EnemyTest
gameobject that, through an EnemyDmg
script, instantiates a damage number whenever a weapon hits it.我有一个
EnemyTest
游戏对象,它通过EnemyDmg
脚本在武器击中它时实例化一个伤害数字。 I would like to put a script on the damage number prefab that will make it move in a random direction in 2-dimensional space.我想在损坏数字预制件上放置一个脚本,使其在二维空间中以随机方向移动。 I know other people have asked this, but the thing is, I would like to be able to move the damage number without rotating it, so that it can still be easily read.
我知道其他人已经问过这个问题,但问题是,我希望能够在不旋转的情况下移动损坏数字,以便仍然可以轻松阅读。 I am planning on putting the code for the damage number movement in a new script on the prefab, contained within a
void Awake()
method.我计划将损坏数字移动的代码放在预制件上的新脚本中,包含在
void Awake()
方法中。
This is the EnemyDmg script:这是 EnemyDmg 脚本:
public class EnemyDmg : MonoBehaviour
{
GameObject EnemyCanvas;
public GameObject DmgNmbr;
void Start()
{
EnemyCanvas = this.gameObject.transform.GetChild(0).gameObject;
}
void OnCollisionEnter2D(Collision2D Collider)
{
if (Collider.gameObject.tag == "Weapon")
{
Debug.Log("Enemy Hit!");
Instantiate(DmgNmbr, EnemyCanvas.transform);
}
}
}
As it currently is, this is what happens when a weapon hits the enemy: Google Drive Video .就目前而言,这就是武器击中敌人时发生的情况: Google Drive Video 。 I would like the yellow number to fly off of the enemy in a random direction, although it doesn't have to go very far.
我希望黄色数字可以随机方向从敌人身上飞走,尽管它不必飞得很远。 From this perspective, the x-axis is left and right, and the y-axis is up and down.
从这个角度看,x轴是左右,y轴是上下。
https://answers.unity.com/questions/1446119/moving-a-non-player-object-in-a-random-direction-w.html https://answers.unity.com/questions/1446119/moving-a-non-player-object-in-a-random-direction-w.html
In that link someone has given a recipe for moving an object in a random direction.在该链接中,有人给出了在随机方向上移动对象的方法。 However, I could not understand what exactly you do ask.
但是,我不明白你到底在问什么。
private Vector3 RandomVector(float min, float max) {
var x = Random.Range(min, max);
var y = Random.Range(min, max);
var z = Random.Range(min, max);
return new Vector3(x, y, z);
}
void Start()
{
var rb = GetComponent<Rigidbody>();
rb.velocity = RandomVector(0f, 5f);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.