unity中控制移动的几个方法

1.transform方式

  1. 直接改变position:这种方式不会考虑collider的碰撞,但是好像在最新的版本中也会考虑到,行不行自己可以实验,方式就是直接改变transform.position即可,代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    //移动速度
    public float _moveSpeed = 5;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
    	//得到wsad的按下
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        //每帧的运行,实际上的速度要乘上 time.deltaTime,直接修改transform,也会考虑Rigidbody的碰撞了。
        transform.position = transform.position + new Vector3(h,0,v)
    }
}

  1. 进行translate()的移动,基本上和上面的一样,只不过移动的逻辑是朝某个方向 * 移动速度 * 时间间隔
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    //移动速度
    public float _moveSpeed = 5;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
    	//得到wsad的按下
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        //调用Translate方法,里面是方向*速度*时间间隔
        transform.Translate(new Vector3(h,0,v)*_moveSpeed*Time.deltaTime);
    }
}

Rigidbody组件方式

  1. addForce(),添加方向力的方式,因为是刚体,所以获取刚体组件,然后添加一个带有方向的里即可,unity手册中的例子如下:
using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	void FixedUpdate() {
		rigidbody.AddForce(Vector3.up * 10);
	}
}// Adds a force upwards in the global coordinate system
//在全局坐标系统添加一个向上的力

  1. velocity直接修改速度,unity中的代码如下:
using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	void FixedUpdate() {
		if (Input.GetButtonDown("Jump"))
			//直接给一个向上的速度
			rigidbody.velocity = new Vector3(0, 10, 0);

	}
}
  1. MovePosition()对于运动学刚体,它基于刚体的运动应用摩擦力。这个让你模拟刚体位于移动平台之上的情况。如果你想其他的刚体与运动学刚体交互,你需要在FixedUpdate函数中移动它。untiy中的例子如下:
using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	private Vector3 speed = new Vector3(3, 0, 0);
	void FixedUpdate() {
		rigidbody.MovePosition(rigidbody.position + speed * Time.deltaTime);
	}
}
发布了201 篇原创文章 · 获赞 210 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/104693620
今日推荐