Unity基础实践小项目(飞机大战)——四元数的运用

目录

飞机代码:

子弹代码:


主要提供飞机代码以及子弹代码。其中飞机代码中提供了子弹的发射数量等等发射逻辑。子弹代码中包含子弹运动逻辑。以下代码仅供参考。

飞机代码:

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public enum E_FireType
{
    One,
    Two,
    Three,
    Round
}
public class Plan : MonoBehaviour
{
    private E_FireType nowType= E_FireType.One;
    public GameObject bullet;
    //设置子弹数量
    public int roundNum = 4;

    // Update is called once per frame
    void Update()
    {
        //设置一个键盘选择输入
        if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            nowType= E_FireType.One;
        }
        else if(Input.GetKeyDown(KeyCode.Alpha2))
        {
            nowType= E_FireType.Two;
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            nowType= E_FireType.Three;
        }
        else if(Input.GetKeyDown(KeyCode.Alpha4))
        {
            nowType = E_FireType.Round;
        }
        //设置空格输出开炮
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Fire();
        }

    }
    private void Fire()
    {
        switch(nowType)
        {
            case E_FireType.One:
                Instantiate(bullet,this.transform.position,this.transform.rotation);
                break;
            case E_FireType.Two:
                Instantiate(bullet,this.transform.position-this.transform.right*0.5f,this.transform.rotation);
                Instantiate(bullet, this.transform.position + this.transform.right * 0.5f, this.transform.rotation);
                break;
           case E_FireType.Three:
                //面朝向
                Instantiate(bullet, this.transform.position, this.transform.rotation);
                Instantiate(bullet, this.transform.position, this.transform.rotation*Quaternion.AngleAxis(-20,Vector3.up));
                Instantiate(bullet, this.transform.position, this.transform.rotation * Quaternion.AngleAxis(20, Vector3.up));
                break;
            case E_FireType.Round:
                float angle = 360 / roundNum;
                for(int i=0; i<roundNum; i++)
                {
                    Instantiate(bullet, this.transform.position, this.transform.rotation * Quaternion.AngleAxis(i*angle, Vector3.up));
                }
                break;

        }
    }
}

子弹代码:

子弹是做成预制体储存起来的,以下是子弹逻辑代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float moveSpeed=20f;
    void Start()
    {
        //延迟5秒清空发射的子弹
        Destroy(this.gameObject,5);
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
    }
}

要想做一个完整的飞机大战程序靠上面的代码是远远不够的,但是提供了最基本的逻辑代码,希望能够给你带来帮助。

猜你喜欢

转载自blog.csdn.net/2303_76354097/article/details/133951339