【Unity NGUI】学习笔记(二)之英雄攻击和装备武器
unity,ngui,装备武器,英雄攻击2016-07-26
玩魔兽世界的时候,游戏人物可以行走,奔跑,攻击,死亡等等行为,今天继续结合上一个案例【Unity NGUI】学习笔记(一):英雄选择,皮肤更换上给英雄添加动作行为。
给英雄准备奔跑 攻击 死亡动画模型
1. 在HeroSelect脚本添加新事件方法来执行英雄的动作,代码如下
public void HeroAni(string aniName)
{
curHero.GetComponent<Animation>().Play(aniName);
}2.分别给sprite添加box Collider和UIbutton,并在OnClick里添加将HeroSelect的HeroAni方法,这样人物就可以有动作了。下面是一个英雄死亡的动作。
1.创建英雄武器库,考虑到武器较多,这里使用代码动态实现武器的显示。
using UnityEngine;
using System.Collections;
public class HeroWeapons : MonoBehaviour {
public UIAtlas mAtlas;
void Start()
{
int rowIndex = 0,colIndex=0;
foreach (UISpriteData sprite in mAtlas.spriteList)
{
if (sprite.name.StartsWith("btn_wp"))
{
UISprite btn= NGUITools.AddSprite(gameObject, mAtlas, sprite.name);
btn.transform.localPosition = new Vector3(-455+60*colIndex, -10-35*rowIndex, 0);
colIndex++;
if (colIndex >= 2)
{
colIndex = 0;
rowIndex++;
}
btn.height = 30;
btn.width = 60;
btn.name = sprite.name;
NGUITools.AddWidgetCollider(btn.gameObject);
btn.gameObject.AddComponent<UIButton>();
btn.gameObject.AddComponent<WeaponClick>();
}
}
}
}
效果图如下:
2.创建Resources文件夹,将全部武器预制体拷贝到文件夹下。在结构试图里每个英雄的子级都有个Bip001 Weapon,它是用来给英雄装备武器的,我们只要把武器的父坐标等于Bip001 Weapon,就能实现我们要的效果。
实现代码如下
using UnityEngine;
using System.Collections;
public class WeaponClick : MonoBehaviour
{
public static GameObject currWeapon;
void OnClick()
{
if (currWeapon != null)
{
Destroy(currWeapon);
}
currWeapon = Instantiate(Resources.Load<GameObject>("weapons/" + name.Substring(4)));
currWeapon.transform.parent = GameObject.Find("Bip001 Weapon").transform;
currWeapon.transform.localScale = Vector3.one;
currWeapon.transform.localRotation = Quaternion.Euler(0, 0, 180);
currWeapon.transform.localPosition = Vector3.zero;
}
}