本篇写的2D动画 主要是控制人物行走方向和播放的动画帧

时间:2023-02-07 20:08:21

自己没有找到4组合适的动画 无法看的很清楚 只能片面的截一张

用GUI生成了几个按钮来控制图中的Cube

记得相机弄成2D视角

本篇写的2D动画 主要是控制人物行走方向和播放的动画帧

如果你有合适的动画 放进相应的资源文件夹中即可

主要代码:
using UnityEngine;
using System.Collections;
public class AA : MonoBehaviour {
// Use this for initialization
private GameObject hero;
private bool keyUp;
private bool keyDown;
private bool keyLeft;
private bool keyRight;
private float time;
private float fps=10;
private int nowFram;
private Object[] animUp;
private Object[] animDown;
private Object[] animLeft;
private Object[] animRight;
private Object[] nowAnim;
private Object[] backAnim;
void Start () {

hero=GameObject.Find("hero");
animUp=Resources.LoadAll("up");
animDown=Resources.LoadAll("down");
animLeft=Resources.LoadAll("left");
animRight=Resources.LoadAll("right");
nowAnim=animDown;
backAnim=animDown;
}

// Update is called once per frame
void OnGUI () {

keyUp=GUILayout.RepeatButton("up");
keyDown=GUILayout.RepeatButton("down");
keyLeft=GUILayout.RepeatButton("left");
keyRight=GUILayout.RepeatButton("right");
}
void FixedUpdate(){
if(keyUp){
SetAnimation(animUp);
hero.transform.Translate(Vector3.up*0.01f);
}
if(keyDown){
SetAnimation(animDown);
hero.transform.Translate(-Vector3.up*0.01f);
}
if(keyLeft){
SetAnimation(animLeft);
hero.transform.Translate(Vector3.forward*0.01f);
}
if(keyRight){
SetAnimation(animRight);
hero.transform.Translate(-Vector3.forward*0.01f);
}
DrawAnimation(nowAnim);
}
void SetAnimation(Object[] tex){
Debug.Log("ing tex in for");
nowAnim=tex;
if(!backAnim.Equals(nowAnim)){
nowFram=0;
backAnim=nowAnim;
}
}
void DrawAnimation(Object[] tex){
time+=Time.deltaTime;
if(time>=1/fps){
nowFram++;
time=0;
if(nowFram>=tex.Length){
nowFram=0;
}
}
hero.renderer.material.mainTexture=(Texture2D)tex[nowFram];
}
}