ais*_*iya -29 c# rotatetransform rotation mouseevent unity-game-engine
我创建了一个项目,当我们触摸它时旋转立方体.当用户停止触摸立方体时,我希望立方体返回其原始位置.下面我添加了旋转立方体的源代码:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class dr : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
#endregion
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
void OnMouseUp()
{
// rotating flag
_isRotating = false;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑过的代码: - 使用UnityEngine; 使用System.Collections;
[RequireComponent(typeof运算(MeshRenderer))]
公共类别:MonoBehaviour {
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
private Quaternion original;
#endregion
void start(){
original = transform.rotation;
}
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
public void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
public void OnMouseUp()
{
// rotating flag
_isRotating = false;
transform.rotation = original;
}
Run Code Online (Sandbox Code Playgroud)
}
"我试图旋转沙发的3D模型并返回其开始旋转.但如果我使用此代码" 无论何时我不再触摸沙发,它会转向**背面的沙发"**我希望它返回到初始旋转.你最初可以看到这是沙发的样子,如果我停止触摸,它会回到沙发的背面.如果我停止旋转,我希望它再次回到正面
当用户停止触摸立方体时,我希望立方体返回其原始位置
我无法确切地说出你正在努力解决这个问题的哪一部分,但你可以简单地在Start或Awake函数中获取GameObject的位置,然后transform.position在OnMouseUp调用时将其设置为该值.
private Vector3 originalPos;
void Start()
{
//Get the original position
originalPos = transform.position;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original position
transform.position = originalPos;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
对于轮换,它也是一样的.只需使用Quaternion而transform.rotation不是Vector3和transform.position.
private Quaternion originalPos;
void Start()
{
//Get the original rotation
originalPos = transform.rotation;
}
void OnMouseUp()
{
_isRotating = false;
//Reset GameObject to the original rotation
transform.rotation = originalPos;
}
Run Code Online (Sandbox Code Playgroud)
您仍然需要将其合并到答案中的原始代码中.如果这是你无法做到的事情,那么请考虑在这里观看Unity的脚本编写教程.
| 归档时间: |
|
| 查看次数: |
3017 次 |
| 最近记录: |