下面为播放动画的代码
using UnityEngine;using System.Collections;
public class playerMove : MonoBehaviour {
//图片包含多少张动作
public int conlumnSize=10;
//每秒播放的帧数
public int conlumnSecond=10;
//运动方向
public bool direction;
//图片的单位偏移
float frameRate = 0;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
//控制播放关键帧动画
public void Move(int conlumnSize,int conlumnSecond,bool direction) {
//当前播放动画的帧数
int index = (int)(Time.time * conlumnSecond);
index = index % conlumnSize;
//图片的单位偏移
frameRate = 1.0F / conlumnSize;
//偏移量 renderer的属性
Vector2 offset;
//大小 renderer的属性
Vector2 size;
if (direction)
{
size = new Vector2(frameRate,1);
offset = new Vector2(index*size.x,0);
}
else
{
size = new Vector2(-frameRate, 1);
offset = new Vector2(-index * size.x, 0);
}
//将当前的帧数赋给人物
renderer.material.mainTextureOffset = offset;
renderer.material.mainTextureScale = size;
}
}
接下来在playerController添加控制人物动画
using UnityEngine;
using System.Collections;
public class playerController : MonoBehaviour {
//定义各种不同状态的材质
public Material idleMaterial;
public Material runMaterial;
public Material dieMaterial;
public Material jumpMaterial;
public Material celebrateMaterial;
//定义速度
public float runSpeed = 0.1F;
public float jumpSpeed = 2.0F;
//是否可以跳
bool jumpEnable;
//运动方向
bool moveDirection;
//任务运动的力
Vector3 griv ;
//获取组件
CharacterController cc;
playerMove pm;
//施加向下的大小
float grivity = 20.0F;
// Use this for initialization
void Start () {
pm = (playerMove)gameObject.GetComponent("playerMove");
cc = (CharacterController)gameObject.GetComponent("CharacterController");
}
// Update is called once per frame
void Update () {
//人物是否在地面
if (cc.isGrounded)
{
//在地面可以跳跃
jumpEnable = true;
//获取水平方向上的移动
griv = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
//如果没有移动
if (griv.x==0)
{
renderer.material = idleMaterial;
}
//如果向右移动
else if (griv.x > 0)
{
//改变材质
renderer.material = runMaterial;
//播放向右动画
pm.Move(10, 10, false);
//在水平方向添加运动力
griv.x *= runSpeed;
//并判断当前方向
moveDirection = true;
}
//向左移动
else if (griv.x < 0)
{
//改变材质
renderer.material = runMaterial;
//播放向左动画
pm.Move(10, 10, true);
//在水平方向添加运动力
griv.x *= runSpeed;
//并判断当前方向
moveDirection = false;
}
//是否跳跃
if (Input.GetButton("Jump") && jumpEnable)
{
//改变材质
renderer.material = jumpMaterial;
//左跳跃
if (moveDirection)
{
pm.Move(11, 11, false);
}
//右跳跃
else if (!moveDirection)
{
pm.Move(11, 11, true);
}
//在竖直方向添加力
griv.y = jumpSpeed;
}
}
//在空中
if (!cc.isGrounded)
{
//不能跳跃
jumpEnable = false;
//右转
if (Input.GetAxis("Horizontal") > 0)
{
renderer.material = runMaterial;
pm.Move(10, 10, false);
}
//左转
else if (Input.GetAxis("Horizontal") < 0)
{
renderer.material = runMaterial;
pm.Move(10, 10, true);
}
}
// 施加向下的力 模拟重力
griv.y -= grivity * Time.deltaTime;
//控制人物运动
cc.Move(griv);
}
}