如何在unity3d开发2d游戏中控制摄像机移动以及主角移动

来源:互联网 发布:ultraiso mac版下载 编辑:程序博客网 时间:2024/06/10 03:33
unity3d开发2d游戏中有了摄像机照射的区域以及背景地图的宽高尺寸那么就可以在代码中编写逻辑判断条件啦。下面我们来使用简单的代码控制摄像机移动以及主角移动。
01using UnityEngine;
02using System.Collections;
03
04public class Controller : MonoBehaviour
05{
06
07 //动画数组
08 private Object[] anim;
09 //主角对象
10 private GameObject hero;
11 //限制一秒多少帧
12 private float fps = 10;
13 //帧序列
14 private int nowFram;
15 //记录当前时间
16 private float time;
17
18 void Start ()
19 {
20 //得到资源名称为down文件夹中的所有对象资源
21 anim = Resources.LoadAll("down");
22 //得到主角的对象
23 hero = GameObject.Find("hero");
24 }
25
26 void FixedUpdate ()
27 {
28 //上、下、左、右平移摄像机
29 if (Input.GetKey (KeyCode.A))
30 {
31 transform.Translate(-0.01f,0,0);
32
33 }
34
35 if(Input.GetKey (KeyCode.D))
36 {
37 transform.Translate(0.01f,0,0);
38 }
39
40 if (Input.GetKey (KeyCode.W))
41 {
42 transform.Translate(0,0.01f,0);
43 }
44
45 if(Input.GetKey (KeyCode.S))
46 {
47 transform.Translate(0,-0.01f,0);
48 }
49
50 //上、下、左、右平移主角
51 if (Input.GetKey (KeyCode.J))
52 {
53
54 hero.transform.Translate(0.001f,0,0);
55 }
56
57 if(Input.GetKey (KeyCode.L))
58 {
59
60 hero.transform.Translate(-0.001f,0,0);
61 }
62
63 if (Input.GetKey (KeyCode.I))
64 {
65 hero.transform.Translate(0,0,-0.001f);
66 }
67
68 if(Input.GetKey (KeyCode.K))
69 {
70 hero.transform.Translate(0,0,0.001f);
71 }
72
73 DrawAnimation(anim);
74 }
75
76 void DrawAnimation(Object[] tex)
77 {
78
79 //计算限制帧的时间
80 time += Time.deltaTime;
81 //超过限制帧切换贴图
82 if(time >= 1.0 / fps){
83 //帧序列切换
84 nowFram++;
85 //限制帧清空
86 time = 0;
87 //超过帧动画总数从第0帧开始
88 if(nowFram >= tex.Length)
89 {
90 nowFram = 0;
91 }
92 }
93 //将对应的贴图赋予主角对象,强制将资源文件转换成贴图
94 hero.renderer.material.mainTexture = (Texture)tex[nowFram];
95 }
96}
0 0
原创粉丝点击