子弹发射
要求:
- 定时发送子弹
- 通过键盘控制左右移动
定时器 :每0.4s发射一个子弹
- 定时发射子弹, 通过预制体不断地创建新的“子弹”实例。
- 子弹发射后,沿着y轴一直移动,超出屏幕边界后销毁。
游戏对象:飞机,子弹(预制体)
“飞机” 挂载:MyJet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyJet : MonoBehaviour
{
public GameObject myPrefab;
private float interval = 0.4f;
private float count = 0;
void Start()
{
Application.targetFrameRate = 60;
}
void Update()
{
count += Time.deltaTime;
if (count >= interval)
{
count = 0;
Fire();
}
}
private void Fire()
{
Vector3 pos = transform.position + new Vector3(0, 1f, 0);
GameObject bullet = Instantiate(myPrefab, pos, transform.rotation);
}
}
“子弹” 挂载: MyBullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyBullet : MonoBehaviour
{
void Start()
{
}
void Update()
{
float step = 5.5f * Time.deltaTime;
transform.Translate(0, step, 0, Space.Self);
Vector3 sp = Camera.main.WorldToScreenPoint(transform.position);
if (sp.y > Screen.height)
{
Destroy(this.gameObject);
}
}
}
键盘控制:实现箭头上下左右移动
Input.GetKeyDown(key) -------- 键盘按下事件 Input.GetKeyUp(key) -------- 键盘抬起事件 Input.GetKey(key) -------- 状态检查,某键是否被按下 在MyJet.cs中加一段探测左右是否被按下,若按下则随后移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyJet : MonoBehaviour
{
public GameObject myPrefab;
private float interval = 0.4f;
private float count = 0;
void Start()
{
Application.targetFrameRate = 60;
}
void Update()
{
count += Time.deltaTime;
if (count >= interval)
{
count = 0;
Fire();
}
float step = 2.5f * Time.deltaTime;
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(-step,0,0);
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(step,0,0);
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(0,step,0);
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(0,-step,0);
}
}
private void Fire()
{
Vector3 pos = transform.position + new Vector3(0, 1f, 0);
GameObject bullet = Instantiate(myPrefab, pos, transform.rotation);
}
}
|