用c#编写一个2d敌人

时间:2015-07-22 16:08:50

标签: c# unity3d 2d

我一直在研究游戏中的敌人,但感觉代码很笨拙,似乎也不起作用。我将代码放入我的播放器脚本和敌人脚本中。播放器脚本如下:

编辑:抱歉不够清楚,以下是不起作用的代码行以及我希望他们做的事情:

 void OnTriggerEnter2D (Collider2D other)
    {
        if (other.gameObject.tag == "Enemy") 
    {
        Destroy (this.gameObject);
    }
    }

我在这段代码中想要的是当玩家遇到具有“Enemy”标签的敌人或物体时,触摸该物体会破坏或杀死玩家物体。

void OnTriggerEnter2D (Collider2D other)
{
    if (other.gameObject.tag == "Killable")
    {
        Debug.Log ("entering killzone!");
        Destroy (other.gameObject);
        Instantiate (DeadStar, transform.position, Quaternion.identity);
        this.gameObject.SetActive (false);
        }
    }
}

这段代码是从以前的游戏中松散复制过来的,它有一些杀戮区域,当它接触到包含这个脚本的任何对象时,会破坏播放器对象。 (播放器标记为“Killable”)

希望这个编辑有所帮助,我有点累,忘了指定事情,抱歉。

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour 
{   
    public float JumpSpeed;
    public float Scale;
    public string JumpKey;
    public string LeftKey;
    public string RightKey;
    public float speed;
    public GameObject Player;
    public Rigidbody2D rb;

    void OnTriggerEnter2D (Collider2D other)
    {
        if (other.gameObject.tag == "Enemy") 
    {
        Destroy (this.gameObject);
    }
    }

    void Start()
    {
        GetComponent<Rigidbody2D>().freezeRotation = true;       /*GetComponent<Rigidbody>().angularVelocity = Vector3.zero;*/
    rb = GetComponent (typeof(Rigidbody2D)) as Rigidbody2D;
}
void FixedUpdate () 
{
    Vector3 hold = rb.velocity;
    hold.x = 0;
    if (Input.GetKey (LeftKey))
    {
        hold.x -= speed;
    }
    if (Input.GetKey (RightKey)) 
    {
        hold.x += speed;
    }
    if (Input.GetKeyDown (KeyCode.Space))
    {
        hold.y = JumpSpeed; 
    } 
    rb.velocity = hold;
}

}

敌人脚本如下:

using UnityEngine;
using System.Collections;

public class EnemyKillzone : MonoBehaviour {
public GameObject DeadStar;
public GameObject Player;


void OnTriggerEnter2D (Collider2D other)
{
    if (other.gameObject.tag == "Killable")
    {
        Debug.Log ("entering killzone!");
        Destroy (other.gameObject);
        Instantiate (DeadStar, transform.position, Quaternion.identity);
        this.gameObject.SetActive (false);
        }
    }
}

0 个答案:

没有答案