Question by
andze1 · Apr 08, 2020 at 03:39 PM ·
rotate objectselecting objects
Selecting objects in game and rotating it
I have a script here in C# that lets me rotate a object (by attaching the script to it) 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:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
private Vector2 firstPressPos;
private Vector2 secondPressPos;
private Vector2 currentSwipe;
private Vector3 previousMousePosition;
private Vector3 mouseDelta;
private float speed = 200f;
public GameObject target;
void Update()
{
Swipe();
Drag();
}
void Drag()
{
if (Input.GetMouseButton(1))
{
mouseDelta = Input.mousePosition - previousMousePosition;
mouseDelta *= 0.1f; // reduction of rotation speed
transform.rotation = Quaternion.Euler(mouseDelta.y, -mouseDelta.x, 0) * transform.rotation;
}
else
{
if (transform.rotation != target.transform.rotation)
{
var step = speed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, target.transform.rotation, step);
}
}
previousMousePosition = Input.mousePosition;
}
void Swipe()
{
if (Input.GetMouseButtonDown(0))
{
firstPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
}
if (Input.GetMouseButtonUp(0))
{
secondPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
currentSwipe.Normalize();
if (LeftSwipe(currentSwipe))
{
target.transform.Rotate(-45, 0, 0, Space.World);
}
else if (RightSwipe(currentSwipe))
{
target.transform.Rotate(45, 0, 0, Space.World);
}
else if (UpLeftSwipe(currentSwipe))
{
target.transform.Rotate(45, 0, 0, Space.World);
}
else if (DownRightSwipe(currentSwipe))
{
target.transform.Rotate(-45, 0, 0, Space.World);
}
}
}
bool LeftSwipe(Vector2 swipe)
{
return currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f;
}
bool RightSwipe(Vector2 swipe)
{
return currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f;
}
bool UpLeftSwipe(Vector2 swipe)
{
return currentSwipe.y > 0 && currentSwipe.x < 0f;
}
bool DownRightSwipe(Vector2 swipe)
{
return currentSwipe.y < 0 && currentSwipe.x > 0f;
}
}
Comment