Unity发射子弹

下面是发射子弹的代码

(以一个飞船发射子弹为例子)

飞机的代码

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

public class playercontroller : MonoBehaviour {

    public float movespeed = 5f;       //飞行速度 

    public Transform shell;    //子弹

    Vector3 movement;  //方向矢量
    Rigidbody playerrigidbody; //定义飞机的rigidbody

    GameObject enemy;  //敌人

    void Awake()
    {
        enemy = GameObject.FindGameObjectWithTag("enemy");
                //通过tag 找到敌人
    }

    void Start () {

        playerrigidbody = GetComponent<Rigidbody>();//获取飞机的rigidbody
    }

     void Update()
    {

        if (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0))
        {
            Instantiate(shell,transform.position, shell.transform.rotation);     //发射子弹的代码(实例化一个子弹)
        }
    }



    void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        move(h, v);

    }

//飞机飞行的代码
    void move(float h,float v)
    {
        movement.Set(h, 0f, v);
        movement = movement.normalized * movespeed * Time.deltaTime;
        transform.position = movement + transform.position;
        playerrigidbody.MovePosition(transform.position);
    }

//飞机的碰撞器上有一个触发器
//飞机撞到别的物体就爆炸
     void OnTriggerEnter(Collider other)
    {
        if (other.gameObject == enemy)
        {
            score.Score += 10;
            Destroy(enemy.gameObject,0f);
            Destroy(this.gameObject, 0f);

        }
    }



}

子弹的代码

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

public class shell : MonoBehaviour {

    public float shell_speed = 10f;  //子弹飞行速度

    protected Transform m_transform;  

    GameObject enemy;  //敌人

    int scorevalue = 5;

     void Awake()
    {
        enemy = GameObject.FindGameObjectWithTag("enemy");

    }
    void Start()
    {
        m_transform = this.transform;
        Destroy(this.gameObject, 1f);  //发射后1秒Destory子弹
    }

    void Update()
    {
        m_transform.Translate(new Vector3(0, 0, shell_speed * Time.deltaTime));      //子弹沿着z轴方向飞行
    }


//子弹撞到敌人后敌人消失
     void OnTriggerEnter(Collider other)
    {
        if (other.gameObject == enemy)
        {
            score.Score = score.Score+scorevalue;
            Destroy(enemy.gameObject,0f);

        }
    }

}

新人练手,不妥之处望大神们指教
个人觉得这个代码有点麻烦,希望有大神能讲一个简单的代码

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rainbow oreo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值