简体   繁体   English

Unity-如何使对象移动然后停止?

[英]Unity-How do I make an object move and then stop?

I'm playing around with a space shooter tutorial I found on the unity website, and I'm trying to make a boss enemy that appears when I reach a certain amount of points. 我正在玩在统一网站上找到的太空射击教程,并且我试图使当达到一定数量点时出现的老板敌人。 But I can't figure out how to make the boss move to the center of the screen. 但是我不知道如何使老板移动到屏幕中央。 I think it has something to do with the mover script I made for the other enemies. 我认为这与我为其他敌人制作的推动者脚本有关。 The other enemies move all the way to the bottom of the screen. 其他敌人一直移动到屏幕底部。 How can I make a boss mover script that just has it move half way on the screen? 如何制作仅在屏幕上移动一半的老板移动脚本?

public class Mover : MonoBehaviour {
public float speed;
private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
    rb.velocity = transform.forward * speed;
}
}

I would use the MovePosition function of the rigidbody as follow : 我将使用MovePosition函数,如下所示:

Vector3 screenCenter ;

void Start()
{
    rb = GetComponent<Rigidbody>();
    screenCenter = Camera.main.ViewportToWorldPoint(new Vector3(0.5,0.5, rb.position.y)); // If I remember right, thte game is a top-down game, right?
}

void FixedUpdate()
{
    Vector3 direction = ( screenCenter - rb.position );
    float distance = Vector3.Distance( screenCenter, rb.position ) ;

    if( distance > Mathf.Epsilon )
        rb.MovePosition(rb.position + speed * direction / distance * Time.deltaTime);
}

You can stop the object by using the following: 您可以使用以下命令停止对象:

rb.velocity = Vector3.zero; rb.velocity = Vector3.zero;

to test it you can do something like the following: 要测试它,您可以执行以下操作:

   private void Update() {
    if (Input.GetKeyDown(KeyCode.S)) {
        rb.velocity = Vector3.zero;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM