unity的三种物体移动方法

本文详细介绍了在Unity游戏开发中三种不同的物体移动方法:使用Rigidbody组件通过速度控制移动,利用CharacterController组件进行移动控制,以及直接使用transform.Translate进行位置变更。针对每种方法的特点及适用场景进行了说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.带有Rigidbody组件的物体移动一般采用 GetComponent<Rigidbody>().velocity  如:

         float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        if(Input.GetButtonDown("Jump"))
            vel = jump;
         else
            vel = GetComponent<Rigidbody>().velocity.y;
        Vector3 movement = new Vector3(h * speed, vel, v * speed);

        movement=Vector3.ClampMagnitude(movement,speed);//限制对角移动的速度和沿着轴线一样
        movement = transform.TransformDirection(movement);//因为velocity是相对全局坐标而言的,所以要把局部坐标转换成全局坐标 如:往左转是相对于移动的物体的 
        GetComponent<Rigidbody>().velocity =movement;

2.带有CharacterController组件的物体一般采用Move(movement)  如:

          Vector3 movement = new Vector3(h * speed, -9.8f, v * speed);
          movement = Vector3.ClampMagnitude(movement, speed);
          movement *= Time.deltaTime;
          movement = transform.TransformDirection(movement);//因为Move是相对全局坐标而言的,所以要把局部坐标转换成全局坐标 如:往左转是相对于移动的物体的 
         _characterController.Move(movement);

3.什么都不带的物体移动一般采用transform.Translate(x,y,z)  如:

注:transform.Translate的移动是不受物理作用的 即:可以穿墙   所以如果不是在平地上移动是不能用translate的

           transform.Translate(movement);//因为一般物体的移动就是在母坐标(不一定是全局如果它有母物体的话)下移动,所以一般不需要用TransformDirection(movement)转换

         



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值