Unity玩家移动简单实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerControler : MonoBehaviour
{
public Rigidbody2D rb;
public float speed;
void Update()
{
Movement();
}
void Movement()
{
rb.velocity = new Vector2(0, 0);
float horizontalmove = Input.GetAxis("Horizontal");
float verticalmove = Input.GetAxis("Vertical");
if (horizontalmove != 0|| verticalmove != 0)
{
rb.velocity = new Vector2(horizontalmove * speed, rb.velocity.y);
rb.velocity = new Vector2(rb.velocity.x, verticalmove * speed);
}
}
}

2D下的简单实现,3D同理,不过得绑个刚体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
public Rigidbody rb;
public float speed;
public void Update()
{
rb.velocity = new Vector3(0, 0, 0);
float horizontalmove = Input.GetAxis("Horizontal");
float verticalmove = Input.GetAxis("Vertical");
if (horizontalmove != 0 || verticalmove != 0)
{
rb.velocity = new Vector3(horizontalmove * speed, 0, rb.velocity.z);
rb.velocity = new Vector3(rb.velocity.x, 0, verticalmove*speed);
}
}
}

丝滑实现详见:https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller/blob/main/Scripts/PlayerController.cs