美文网首页
写一个发射子弹打方块的demo

写一个发射子弹打方块的demo

作者: Tea_R | 来源:发表于2019-01-19 19:31 被阅读0次

2019-01-19

今天写了一个发射子弹打方块的Unity demo

学习地址
Unity零基础入门 - 打砖块 http://www.sikiedu.com/course/77

项目
game界面

可以实现的功能:镜头的上下左右移动,以及建立一个球体,发射球 体

建立模型

在Unity界面创建一个Plane作为地面,创建一些cube叠成一堵墙

tip:Ctrl+d快捷复制,Ctrl+移动可以完成模型按照整数单位移动,旋转,将cube放入新建的Prefabs文件夹中 image.png

并且为cube添加刚体组件,使其有刚体属性
在Prefabs中添加球体,来当做子弹

代码

移动代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
    public float speed = 5;
    // Start is called before the first frame update
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        //Debug.Log(h);
        transform.Translate(new Vector3(h,v,0) * Time.deltaTime * speed);
    }
}

发射代码

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

public class shoot : MonoBehaviour{
    // Start is called before the first frame update
    public GameObject bullet;//子弹
    public float speed = 20;//速度
    void Start(){
    }

    // Update is called once per frame
    void Update(){
        if (Input.GetMouseButtonDown(0))
        {
            GameObject b = GameObject.Instantiate(bullet, transform.position, transform.rotation);//新建一个子弹,位置为摄像头位置
            Rigidbody rgb = b.GetComponent<Rigidbody>();//获取子弹的刚体属性
            rgb.velocity = transform.forward * speed;//赋予子弹初速度
        }

    }
}

tip:拖拽可赋予游戏物体属性

相关文章

网友评论

      本文标题:写一个发射子弹打方块的demo

      本文链接:https://www.haomeiwen.com/subject/ydlzdqtx.html