枪械原型

给Player添加一个Sprite——Square子对象,命名为Gun,将Scale-X设为0.5,Scale-Y设为0.1,Position-X设为0.5,颜色设为黑色

Gun

接下来给Gun添加一个Sprite——Square子对象,命名为Bullet,将Scale-X设为0.2,Position-X设为0.4,颜色设为橙色。并且给子弹挂载BoxCollider2D和Rigidbody2D,并将其Rigidbody的Gravity Scale设为0。

Bullet

设置开枪脚本

在Scripts文件夹新建Bullet脚本,并挂载在Bullet上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using UnityEngine;

namespace ShootingEditor2D
{
public class Bullet : MonoBehaviour
{
private Rigidbody2D m_Rigidbody;

private void Awake()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}

private void Start()
{
m_Rigidbody.velocity = Vector2.right * 10;
}
}
}

接着,我们来实现每次按下J键,发射一次子弹的功能。

发射子弹

在Scripts文件夹内新建Gun脚本,挂载在Gun上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using UnityEngine;

namespace ShootingEditor2D
{
public class Gun : MonoBehaviour
{
private Bullet m_Bullet;

private void Awake()
{
m_Bullet = transform.Find("Bullet").GetComponent<Bullet>();
}

public void Shoot()
{
//设置父级生成Bullet
//var bullet = Instantiate(m_Bullet, transform);

//不设置父级生成Bullet
var bullet = Instantiate(m_Bullet, m_Bullet.transform.position, m_Bullet.transform.rotation);
//将生成的Bullet的缩放继承之前Bullet的世界坐标缩放值
bullet.transform.localScale = m_Bullet.transform.lossyScale;

bullet.gameObject.SetActive(true);
}
}
}

修改Player脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using UnityEngine;

namespace ShootingEditor2D
{
public class Player : MonoBehaviour
{
//...
private Gun m_Gun;

//...
private void Awake()
{
//...
m_Gun = transform.Find("Gun").GetComponent<Gun>();
}

private void Update()
{
//...
if (Input.GetKeyDown(KeyCode.J))
{
m_Gun.Shoot();
}
}

//...
}
}

发射子弹

敌人原型

在场景中新建一个Square命名为Enemy,和Player一样,挂载2D刚体和2D碰撞器,锁定Z轴旋转。并将颜色设置为红色

新建一个Tag命名为“Enemy”,应用在Enemy上

Enemy

修改Bullet脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using UnityEngine;

namespace ShootingEditor2D
{
public class Bullet : MonoBehaviour
{
//...

private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Enemy"))
Destroy(collision.gameObject);
}
}
}