在上一篇中使物体来回移动的函数主要是获取键盘操作输入的情况Input.GetKey(),然后物体朝着某一个方向移动

gameObject.transform.Translate(Vector3.up*Time.deltaTime);
 除了这个函数,可以用开发环境自带设置,Input.GetAxis(),然后使物体移动;新建一个文件,命名为MovementOther.cs
using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;public class MovementOther : MonoBehaviour
 {
public 	GameObject Player;
	public float m_speed=5f;
// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
	float horizontal=Input.GetAxis("Horizontal");
	float vertical=Input.GetAxis("Vertical");
	Player.transform.Translate(Vector3.up * vertical * m_speed * Time.deltaTime);
	Player.transform.Translate(Vector3.right * horizontal * m_speed * Time.deltaTime);

}

}

Input.GetAxis()这个用法对应了开发环境中的Input Manager设置,在官方手册的Input Manager用法中描述为

The Input Manager window allows you to define input axes and their associated actions for your Project. To access it, from Unity’s main menu, go to Edit > Project Settings, then select Input Manager from the navigation on the right.如下:

unity2D如何检测左右 unity2d物体移动_unity2D如何检测左右


unity2D如何检测左右 unity2d物体移动_unity_02

这里面Horizontal,对应的是left和right,A/D键,Vertical对应的down和up,W/S键。当然,这里可以自己设置自己习惯的按键,用来替换环境默认设置好的按键。

将脚本赋给二维图形中的左面的圆形。

unity2D如何检测左右 unity2d物体移动_游戏引擎_03


运行一下,使用上下左右键来控制物体移动,能看出来物体在平面上流畅的移动。

这里使用了Vector3下的一些方法。

1、Vector3.back=(0,0,-1)
 2、Vector3.forward=(0,0,1)
 3、Vector3.left=(-1,0,0)
 4、Vector3.right=(1,0,0)
 5、Vector3.down=(0,-1,0)
 6、Vector3.up=(0,1,0)
 7、Vector3.zero=(0,0,0)
 8、Vector3.notallow=(1,1,1)
 二维平面我们使用left/right和up/down,在三维立体空间中我们引用back和forward代表Z轴移动。如果将
 Player.transform.Translate(Vector3.up * vertical * m_speed * Time.deltaTime);
 替换成
 Player.transform.Translate(Vector3.forward * vertical * m_speed * Time.deltaTime);

演示一下能看出来圆形在水平方向上移动顺畅,但是在二维平面的垂直方向,移动不顺畅。那是因为在二维平面上forward代表的Z轴体现效果不明显,所以看着物体是不移动的,换做三维空间中能看到顺畅的移动。

unity2D如何检测左右 unity2d物体移动_unity_04


我们将灯泡图标旁边的2D点一下,让空间变成3D,然后执行程序,移动上下键,能看到物体在Z轴顺畅移动,Z轴是标蓝色的轴。按W键,圆形从远方移动到近距离处。见下图,从左面的三维空间能够看到圆形逐步变大,因为距离我们的视角是变近了。从右图能看到圆形在二维平面上只是较少的上移了一些,与右面的方形物体的水平面相比,可结合上一张图的右图来对比。

unity2D如何检测左右 unity2d物体移动_二维_05


总之,二维平面是三维空间的一部分,学好二维平面,在二维切换三维的过程中,原理是相通的,二维看到的效果可以和三维看到的效果做对比,更能反映空间成像效果。