I have a simple script here in C# that lets me rotate a object (by attaching the script to it) by 90 degrees in either direction which works fine but what i would like to have is to be able to select an object in game and then rotating it by pressing a button. Here is the script i have so far:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Q)) {
transform.Rotate(0,90,0,Space.World);
}
if(Input.GetKeyDown(KeyCode.E)) {
transform.Rotate(0,-90,0,Space.World);
}
}
}
I’m not a very good programmer so it be greatly appreciated if someone could show me how to select the object and then rotate it with this script. Thanks.
Depends how you want to select the object. If you mean doing a ‘mouse pick’ (taking the 2D mouse cursor, finding its point on the camera lense, making a line from that point straight out from the camera and getting any object that intersects with that line then what you want is,
void Update() {
RaycastHit hit;
if(Physics.Raycast(
camera.ScreenPointToRay(Input.mousePosition), // that line I was talking about
out hit, //information about what you have hit
Mathf.Infinity, // cast through the whole world
0x100 // 0x100 is the layer mask for layer 8, so find any collider in layer 8
)) {
hit.collider.gameObject.AddComponent<RotationScript>();
}
}
The simplest way I can think of to do what you want is to use some of the built in events that Unity automatically sends out for objects with colliders, like OnMouseDown, OnMouseOver, or OnMouseDrag. I don’t know the exact behavior you want, but the following would allow you to rotate an object with the mouse and dragging the left mouse button. This will also rotate the object freely, no constraints, relative to your main camera’s orientation, so it looks like you are rotating it with the mouse.
using UnityEngine;
using System.Collections;
public class RotateWithMouse : MonoBehaviour {
public float mouseRotateSpeed = 15f;
void OnMouseDrag()
{
transform.rotation = Quaternion.AngleAxis( -Input.GetAxis("Mouse X") * mouseRotateSpeed, Camera.mainCamera.transform.up) *
Quaternion.AngleAxis( Input.GetAxis("Mouse Y") * mouseRotateSpeed, Camera.mainCamera.transform.right) *
transform.rotation;
}
}