gpt4 book ai didi

Unity3D 中的 C# 脚本仅 debug.log 而不是旋转

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:22 25 4
gpt4 key购买 nike

在我的 unity 3D 项目中,我有一个带有子对象的地平面舞台。当我按下 UI 按钮时,对象应该旋转,如果我松开按钮,旋转应该停止。不幸的是它不起作用。它只显示了我的 Debug.Log 函数,但对象没有旋转。

这是我的脚本:

using System.Collections;
using System.Collections.Generic;
using Unity.Engine;

public class RotateCube : MonoBehaviour
{
public Rigidbody rb;
public rotateStatus = false;
//public float rotationSpeed = 100f;

public void rotateNow()
{
rotateStatus = !rotateStatus;
Debug.Log("Rotation position = " + transform.eulerAngles.y)
}

void Update()
{
if(rotateStatus)
{
rb.transform.Rotate(0, 45, 0, Space.World);
// Also tried it with;
// rb.transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
Debug.Log("Rotation should been happend.");
}
}
}

脚本附加到我的游戏对象。 UI 按钮有一个带有游戏对象的 OnClick 事件,并链接到 rotateNow 函数。

我还尝试了 Input.GetMouseButtonDown(0)Input.GetButtonDown() 方法。哪个可行,但是每次我按下屏幕时使用这些方法,我的对象都会旋转。

这是我在 iPad 上测试控制台时显示的内容:

(Filename: ./Runtime/Export/Debug.bindings.h Line 45)

Rotation should have been happened.

编辑

enter image description here

最佳答案

这会使对象每一帧旋转大约 45° ...这只是为了让你的眼睛快点

你应该使用 Time.deltaTime为了将旋转转换成平滑的“旋转/秒”

Rotate(0, 45 * Time.deltaTime, 0, Space.World);

一旦涉及到Rigidbody,您就应该通过Transform组件设置任何转换,而是使用RigidBody.MoveRotationFixedUpdate 中以旋转对象但保持物理完好

void FixedUpdate()
{
if(rotateStatus)
{
rb.MoveRotation(rb.rotation * Quaternion.Euler(Vector3.up * rotationSpeed * Time.deltaTime));
Debug.Log("Rotation should be happening.");
}
}

if i release the button, the rotation should stop

这不会发生。 Unity 的默认按钮没有实现来告诉您的脚本该按钮不再被按下。

您可以使用 IPointerUpHandler 为此编写您自己的扩展和 IPointerExitHandler接口(interface):

public class ReleaseButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
public UnityEvent onPointerUp;

[SerializeField] private Button button;

private void Awake()
{
if(!button) button = GetComponent<Button>();
}

// according to the Docs this has to be implemented in order to
// receive OnPointerUp events ... though we don'T need it actually
public void OnPointerDown(PointerEventData pointerEventData){ }

public void OnPointerExit(PointerEventData pointerEventData)
{
if(!button.interactable) return;

onPointerUp.Invoke();
}

public void OnPointerUp(PointerEventData pointerEventData)
{
if(!button.interactable) return;

onPointerUp.Invoke();
}
}

将其附加到您的按钮并在 onPointerUp 中引用您的 RotateNow,以便在释放按钮时重置 rotateStatus

关于Unity3D 中的 C# 脚本仅 debug.log 而不是旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com