- Home /
Drag to Rotate Game Object with Mouse
Hi all,
This code works nice in my work but i just want a spin circular rotation with mouse drag like this picture. Anyone can help me ? Thanks.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class rotateController : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 0.5f;
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;
_rotation.z = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
// rotate
//transform.Rotate(_rotation);
transform.eulerAngles += _rotation;
// store mouse
}
}
void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
void OnMouseUp()
{
// rotating flag
_isRotating = false;
}
}
Answer by sairaju · Jul 17, 2017 at 09:22 AM
give a tag name to sphere then the ray cast will be recognize that one only ,it will rotate in only right and left direction ,if u want to move x,y,z means give transform.Rotate (0,(Input .GetAxis("Mouse X")speed -Time .deltaTime),0,Space .World); in place of zeros give (Input .GetAxis("Mouse Y")*speed *Time .deltaTime),(Input .GetAxis("Mouse Z")*speed *Time .deltaTime)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class newrotation : MonoBehaviour { public float speed = 5.0f; Ray r; RaycastHit rh; // Use this for initialization void Start () {
}
// Update is called once per frame
void Update () {
r = Camera.main.ScreenPointToRay (Input .mousePosition);
if(Physics .Raycast (r,out rh,1000))
{
if(rh.collider .gameObject .tag=="rot")
{
if(Input .GetMouseButton (0) )
{
transform.Rotate (0,(Input .GetAxis("Mouse X")*speed *-Time .deltaTime),0,Space .World);
}
}
}
}
}
Your answer
Follow this Question
Related Questions
Weird shaky player behavior (moving through colliders) 0 Answers
Character Movement won't work properly because of the rotation 1 Answer
how to rotate a gameobject in a given direction and stop when it's done 1 Answer
gameobject stops moving correctly when rotating 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers