Skip to main content
 首页 » 编程设计

c#之我如何让敌人在 unity c# 中从屏幕的顶部移动到底部

2024年02月05日9fff_TT

我正在尝试使用 unity 创建一个 2D 太空射击游戏,但我似乎无法让生成的敌人从屏幕顶部移动到屏幕底部,我实际上是 unity 和 c# 的新手,而且我无法弄清楚我的代码有什么问题。

这是我的代码:

using UnityEngine; 
using System.Collections; 
 
public class EnemyControl : MonoBehaviour { 
 
float speed; 
// Use this for initialization 
void Start () { 
    speed = 2f; 
} 
 
// Update is called once per frame 
void Update () { 
    Vector2 position = new transform.position; 
 
    position = new Vector2(position.x, position.y - speed * Time.deltaTime); 
 
    transform.position = position; 
 
    Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0)); 
 
    if(transform.position.y < min.y) { 
    Destroy(gameObject); 
    } 
} 

请您参考如下方法:

这是你应该如何从上到下移动对象

using UnityEngine; 
using System.Collections; 
 
public class EnemyControl : MonoBehaviour { 
   float speed; 
 
    void Start () { 
      speed = 2.0f; 
} 
 
// Update is called once per frame 
void FixedUpdate () { 
 
    godown(); 
 
} 
 
void godown() { 
    transform.position += Vector3.down *speed* Time.deltaTime; 
} 

现在在您的游戏世界中添加另一个对象,您可以将其命名为 destroyer 。将该新对象放置在场景底部。为下落对象指定一个标签名称“fallingObject”。并使用新对象添加此脚本。

using UnityEngine; 
using System.Collections; 
 
public class DestroyCubes : MonoBehaviour 
{ 
void OnCollisionEnter2D(Collision2D col) 
{ 
    if(col.gameObject.name == "fallingObject") 
    { 
        Destroy(col.gameObject); 
    } 
} 
} 

新的脚本名称应该是“DestroyCubes”