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);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值