2401_86219901 2024-08-19 16:09 采纳率: 0%
浏览 7

unity物体旋转脚本这样写怎么有问题啊

请问大家们,为什么我这样进行物体移动时,前进是正常的,但是旋转起来很奇怪,在单独按ad键时,感觉旋转中心在物体的后方

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class move : MonoBehaviour
{
    public float moveSpeed = 10;
    public float angularSpeed = 5;

    public Rigidbody rb;

    public GameObject Camera;

    Vector3 v3 = new Vector3();

    void Start()
    {
        rb = transform.GetComponent<Rigidbody>();

        v3 = Camera.transform.position - transform.position;
    }

    void FixedUpdate()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        transform.Translate(horizontal * moveSpeed * Time.deltaTime, 0, vertical * angularSpeed * Time.deltaTime);

        rb.velocity = transform.forward * vertical * moveSpeed;

        rb.angularVelocity = transform.up * horizontal * angularSpeed;

        Camera.transform.position = transform.position + v3;
    }
}

  • 写回答

2条回答 默认 最新

  • 一直免费一直爽 2024-08-19 16:09
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    你的代码中,物体的旋转中心可能不是物体的中心,而是物体的原点。你可以尝试将物体的旋转中心设置为物体的中心,这样旋转时就会感觉更自然。你可以在Unity编辑器中设置物体的旋转中心,或者在脚本中使用以下代码:

    void Start()
    {
        rb = transform.GetComponent<Rigidbody>();
        rb.centerOfMass = Vector3.zero; // 将物体的旋转中心设置为物体的中心
    
        v3 = Camera.transform.position - transform.position;
    }
    

    另外,你的代码中,物体的前进速度和旋转速度都使用了angularSpeed变量,这可能导致旋转速度过大。你应该分别为前进速度和旋转速度设置不同的变量,例如:

    public float moveSpeed = 10;
    public float rotateSpeed = 5;
    

    然后在FixedUpdate方法中分别使用这两个变量:

    rb.velocity = transform.forward * vertical * moveSpeed;
    rb.angularVelocity = transform.up * horizontal * rotateSpeed;
    

    这样,你的物体在移动和旋转时应该会表现得更自然。

    评论

报告相同问题?

问题事件

  • 创建了问题 8月19日

悬赏问题

  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 为什么在iis上部署网站,服务器可以访问,但是本地电脑访问不了
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数
  • ¥15 ADS时域 连续相位观察方法
  • ¥15 Opencv配置出错
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像