【Unity 3d + C#】2d游戏坦克大战开发详解(二) |
您所在的位置:网站首页 › unity预制体制作 › 【Unity 3d + C#】2d游戏坦克大战开发详解(二) |
二、坦克的移动 我们在上一节中制作了好几个实体,动画实体,还给各个实体都做了预制体,这一节我们通过写脚本让坦克移动并且可以发射子弹。 我们对我们的实体Player创建一个C#脚本,脚本命名为:Player。 创建完成之后,我们的脚本是这样的: using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }我们在Update方法之下,加一个固定更新方法FixedUpdate,然后写一个move方法,来控制玩家的移动。我们看以下代码: void FixedUpdate(){ move (); } //Player's move void move(){ //right and left float rl=Input.GetAxisRaw("Horizontal"); transform.Translate (Vector3.right * moveSpeed * rl * Time.fixedDeltaTime, Space.World); /* priority if you press the Button "W" and "A" at one time,we will priority "A" or "D" */ if (rl != 0) return; //up and down float ud=Input.GetAxisRaw("Vertical"); transform.Translate (Vector3.up * moveSpeed * ud * Time.fixedDeltaTime, Space.World); }我们写过这样的代码之后,保存了代码,等待U3d编译之后,就可以发现坦克可以动了。但是这个时候就会发现很别扭,因为我们无论朝哪个方向走,我们的坦克头都是朝上的。这时候,我们用这个方法补救。 声明私有SpriteRenderer类型sr,调用Awake方法。声明一个Sprite数组 用来存储四个方向坦克的图片,之后在move方法里判断上下左右方向,然后编译。(代码特意带了一个小BUG,希望读者不要一味照搬,学会自己变通使用) using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public float moveSpeed=10; //the tank move speed private SpriteRenderer sr; public Sprite[] tankSprite; //up right down left private void Awake(){ sr = GetComponent (); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void FixedUpdate(){ move (); } //Player's move void move(){ //right and left float rl=Input.GetAxisRaw("Horizontal"); transform.Translate (Vector3.right * moveSpeed * rl * Time.fixedDeltaTime, Space.World); if (rl < 0) sr.sprite = tankSprite [3]; else if (rl > 0) sr.sprite = tankSprite [1]; /* priority if you press the Button "W" and "A" at one time,we will priority "A" or "D" */ if (rl != 0) return; //up and down float ud=Input.GetAxisRaw("Vertical"); transform.Translate (Vector3.up * moveSpeed * ud * Time.fixedDeltaTime, Space.World); if (ud < 0) sr.sprite = tankSprite [0]; else if (ud > 0) sr.sprite = tankSprite [2]; } }写完这些代码以后,我们还不能实现四个方向的变动,那是因为我们没有导入图片,我们打卡U3d工作界面。找到相应的坦克上下左右的方向,再导入到数组中,具体方法如下图所示: 在这之后,点击运行游戏,就可以实现四个方向的走动了。 接下来我们来处理坦克通过障碍的问题!这只需要在需要的实体身上加一个触发器,坦克身上加一个触发器和碰撞器就好了。我们以实体“Wall”为例: 同样的方法,给River、Eagle、Barrir、Player添加上Box Collider 2D。然后我们给Player添加一个Rigibody 2D(目的是为了触发碰撞效果) 这样就完事儿了……坦克的移动就解决了。 小技巧:直接在预制体上进行操作会省很多步骤哟! 转载请注明出处。
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |