ChihHuCheYeh's Blog

Unity2D下移动精灵的几种方法汇总

2018/05/08 Share

Rigbody2D (最优)

方案1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

public float speed = 3; //移动速度
float moveH, moveV; //水平输入(X) 垂直输入(Y)
Rigidbody2D rigidbody2d; //挂在玩家身上的2D刚体
Transform transform2d; //2D坐标
void Start()
{
transform2d = GetComponent<Transform>();
rigidbody2d = GetComponent<Rigidbody2D>();
}

void Update()
{

moveH = Input.GetAxis("Horizontal"); //水平输入
moveV = Input.GetAxis("Vertical"); //垂直输入

//水平位移
transform2d.Translate(Vector3.right * moveH * speed * Time.deltaTime, Space.World);

//垂直位移
transform2d.Translate(Vector3.up * moveV * speed * Time.deltaTime, Space.World);
Debug.Log("X:" + moveH + " -Y:" + moveV);
}

方案2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public float speed; //移动速度
float moveH, moveV; //水平移动(X)与垂直移动(Y)
Rigidbody2D rigidbody2d; //挂在玩家身上的2D刚体

void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}

void Update()
{

Vector2 a = new Vector2(Input.GetAxis("Horizontal") * speed, Input.GetAxis("Vertical") * speed);
rigidbody2d.AddForce(a);
}

Transform

WARRNING:此办法笨到天理不容,通过侦听按键产生位移,代码量不可估量,或许某些时候会有点用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

public float speed = 3; //移动速度
float moveH, moveV; //水平移动(X)与垂直移动(Y)
Rigidbody2D rigidbody2d; //挂在玩家身上的2D刚体
Transform transform2d;
void Start()
{
transform2d = GetComponent<Transform>();
rigidbody2d = GetComponent<Rigidbody2D>();
}

void Update()
{

if (Input.GetKey(KeyCode.A))
{
transform2d.Translate(new Vector2(-0.1f*speed * Time.deltaTime, 0f));
}
if (Input.GetKey(KeyCode.D))
{
transform2d.Translate(new Vector2(0.1f * speed * Time.deltaTime, 0f));
}

//BLAHBLAHBLAH 以此类推
}
CATALOG
  1. 1. Rigbody2D (最优)
  2. 2. Transform