首先在创建demo之前,要准备好:鱼、大炮、子弹游戏体并添加刚体和碰撞体组件。
在完成脚本的编辑之后,分别把脚本挂载到鱼、大炮、子弹 游戏体体上。就能实现简单的大炮开火射击鱼,鱼生命值为0死亡后发生爆炸特效。
后续对游戏进行完善:添加不同的关卡,不同的大炮,不同的鱼,炫酷的特效,声音组件,得分系统,设计友好的界面,添加游戏管理器。。。
言归正传:
首先对fish脚本进行编写:(fish行走的路径和生成分别用splime waypoint、poolManager插件进行实现)
SetDamage方法中,damage指的是子弹打到鱼时的伤害量,当m_life <= 0时获取爆炸特效的prefab,并设置1s后销毁。
using UnityEngine;
using System.Collections;
public class Fish : MonoBehaviour
{
protected Transform m_transform;
public int m_life = 1;
void Start()
{
m_transform = this.transform;
}
// Update is called once per frame
void Update()
{
}
public void SetDamage(int damage)
{
m_life -= damage;
if (m_life <= 0)
{
GameObject prefab = Resources.Load(“explosion”);
GameObject explosion = (GameObject)Instantiate(prefab, m_transform.position, m_transform.rotation);
Destroy(explosion, 1.0f);
GameManager.Instance.SetScore(1);
Destroy(this.gameObject);
}
}
}
子弹脚本核心代码如下:Fire Create 为创建子弹实例,方便后面大炮脚本的调用。
void OnTriggerEnter2D(Collider2D other)中,先获取fish脚本,当fish不为空时,调用SetDamage()方法,伤害值为1,然后销毁子弹游戏体。
using UnityEngine;
using System.Collections;
public class Fire : MonoBehaviour {
protected Transform m_transform;
public float m_moveSpeed = 10.0f;
public static Fire Create(Vector3 pos, Vector3 angle)
{
GameObject prefab = Resources.Load(“Fire”);
GameObject fireSprite = (GameObject)Instantiate(prefab, pos, Quaternion.Euler(angle));
Fire f = fireSprite.AddComponent();
Destroy(fireSprite, 2.0f);
return f;
}
// Use this for initialization
void Start() {
m_transform = this.transform;
}
// Update is called once per frame
void Update() {
m_transform.Translate(new Vector3(0, m_moveSpeed * Time.deltaTime, 0));
}
void OnTriggerEnter2D(Collider2D other)
{
Fish f = other.GetComponent();
if (f == null)
return;
else
f.SetDamage(1);
Destroy(this.gameObject);
}
}
大炮脚本核心代码如下:
在UpdateInput函数实现:计算出大炮到鼠标位置的角度,旋转大炮,并发射子弹。
1、获取鼠标的位置,转为世界坐标。
2、获取大炮的位置
3、按鼠标左键或空格键开火
4、计算鼠标位置和大炮位置之间的角度
5、创建子弹实例,开火。
重点和难点在于:计算鼠标位置和大炮位置之间的角度。
using UnityEngine;
using System.Collections;
public class Cannon : MonoBehaviour {
protected Transform m_transform;
float m_shootTimer = 0;
public AudioClip m_shootClip;
protected AudioSource m_audio;
// Use this for initialization
void Start () {
m_transform = this.transform;
m_audio = m_transform.GetComponent();
}
// Update is called once per frame
void Update () {
m_shootTimer -= Time.deltaTime;
UpdateInput();
}
void UpdateInput()
{
Vector3 ms = Input.mousePosition;
ms = Camera.main.ScreenToWorldPoint(ms);
Vector3 mypos = m_transform.position;
if (Input.GetMouseButton(0) || Input.GetKey(KeyCode.Space))
{
Vector2 targetDir = ms - mypos;
float angle = Vector2.Angle(targetDir, Vector3.up);
if (ms.x > mypos.x)
angle = -angle;
m_transform.eulerAngles = new Vector3(0, 0, angle);
if (m_shootTimer <= 0)
{
m_shootTimer = 1.0f;
Fire.Create(m_transform.TransformPoint(0, 1, 0), new Vector3(0, 0, angle));
m_audio.PlayOneShot(m_shootClip);
}
}
}
}