简体   繁体   中英

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 :

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;

to test it you can do something like the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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