**Unity控制角色移动方式**

Unity控制角色移动方式

动态”是游戏最基本的特性之一,游戏只有动起来才能吸引人。今天主要和大家分享一下我平时通过unity控制主角移动的方式。

1

直接更改角色的transform.position属性(不建议使用,移动有卡顿):

public class MoveControl1 : MonoBehaviour {

public float speed;

// Use this for initialization

void Start () {

    speed = 1f;

}



// Update is called once per frame

void Update () {

    if (Input.GetKey(KeyCode.A))

    {

        transform.position += new Vector3(0.1f, 0, 0);

    }

    else  if (Input.GetKey(KeyCode.D))

    {

        transform.position += new Vector3(-0.1f, 0, 0);

    }

    else if (Input.GetKey(KeyCode.W))

    {

        transform.position += new Vector3(0, 0, 0.1f);

    }

    else if (Input.GetKey(KeyCode.S))

    {

        transform.position += new Vector3(0, 0, -0.1f);

    }

}

}

2

使用transform.Translate方法:

public class MoveControl1 : MonoBehaviour {

public float speed;

// Use this for initialization

void Start () {

    speed = 1f;

}



// Update is called once per frame

void Update () {

    float vertical = Input.GetAxis("Vertical");

    float horizontal = Input.GetAxis("Horizontal");

    transform.Translate(new Vector3(horizontal, 0, vertical) * Time.deltaTime * speed);//注意参数,只传入一个vector是不行的

}

}

3

使用刚体组件:(注意区别:此方法带有物理特性,在抬起按键后会继续移动一点距离)

public class MoveControl2 : MonoBehaviour {

// Use this for initialization

private Rigidbody rigidbody;

private float speed;



void Start () {

    speed = 1f;

    rigidbody = this.GetComponent<Rigidbody>();

}



// Update is called once per frame

void Update () {

    float vertical = Input.GetAxis("Vertical");

    float horizontal = Input.GetAxis("Horizontal");

    if (Input.GetKey(KeyCode.A))

    {

        rigidbody.velocity = Vector3.forward * speed;

    }

    if (Input.GetKey(KeyCode.D))

    {

        rigidbody.velocity = Vector3.back * speed;

    }

    if (Input.GetKey(KeyCode.W))

    {

        rigidbody.velocity = Vector3.left * speed;

    }

    if (Input.GetKey(KeyCode.S))

    {

        rigidbody.velocity = Vector3.right * speed;

    }

}

}

4

使用组件CharacterController:

public class MoveControl3 : MonoBehaviour {

private CharacterController character;

private float speed;

void Start () {

    character = this.GetComponent<CharacterController>();

    speed = 1f;

}

// Update is called once per frame

void Update () {

    MoveControl();

}

void MoveControl()

{

    float horizontal = Input.GetAxis("Horizontal"); //A D 左右

    float vertical = Input.GetAxis("Vertical"); //W S 上 下

    character.Move(new Vector3(horizontal, 0, vertical) * speed * Time.deltaTime);

}

}

5

使用vector3.lerp,movetowards,rigadbody.MovePosition等方法常用于实现移动到固定位置,代码可自行尝试,比较简单

由于篇幅有限,今天就和大家暂时分享这些,除了上述的移动方法外,还可以使用各种好用的插件,包括easy touch,dotween等,插件免费分享给大家,关注我的微信公众号可以查看。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_36696486/article/details/84146555