Rotate object to mouse direction - unity3d

I have this script, that already works
I,m using leanFinger
var c = Camera.main;
var center = rb.position;
var lastPos = _finger.GetWorldPosition(c.transform.position.y, c);
var lastDelta = Vector3.Distance(center, lastPos);
float angle = Mathf.Atan2(lastPos.x, lastPos.z) * Mathf.Rad2Deg;
rb.rotation = Quaternion.Euler(new Vector3(0, angle - initialRotation, 0));
The problem is that my object is rotating in absolute angles, so if it is already rotated, there is a unwanted rotation. I want it to take an initialRotation value, but i don't know how.
Thanks

You can use transform.rotation to access the current rotation of your object: Transform.rotation
You could also use this method for convenience: Transform.LookAt
Simple JS example:
public var target : Transform;
function Update ()
{
transform.LookAt(target);
}

Related

How to make limited camera movement in Unity C#

I am making a FNAF fan game using Unity, and I need limited camera movement, like shown in this video. I've been trying to figure this out but I found no tutorials nor any answers. If you could link a script for this I would be very greatful!
https://vimeo.com/710535461
Attach this code to the camera and you can limit the camera movement by setting two angles in the inspector. Remember that this code limits localEulerAngles values and always must set the camera rotation to zero, To adjust its rotation, place the camera as child of an empty object and then rotate the parent.
public class LimitedCamera : MonoBehaviour
{
public float LimitAngleX = 10f;
public float LimitAngleY = 10f;
private float AngleX;
private float AngleY;
public void Update()
{
var angles = transform.localEulerAngles;
var xAxis = Input.GetAxis("Mouse X");
var yAxis = Input.GetAxis("Mouse Y");
AngleX = Mathf.Clamp (AngleX-yAxis, -LimitAngleX, LimitAngleX);
AngleY = Mathf.Clamp (AngleY+xAxis, -LimitAngleY, LimitAngleY);
angles.x = AngleX;
angles.y = AngleY;
transform.localRotation = Quaternion.Euler (angles);
transform.localEulerAngles = angles;
}
}

Keep camera from rotating around relative z-axis

I'm trying to create camera movement that mimics the behavior of the unity scene editor where you can perform a spherical rotation around the scene with 2d mouse movement. So far the camera is rotating correctly given x or y movement, but dragging diagonally causes the camera to rotate around its relative z-axis until it gets locked. I cannot force the camera to look at the origin relative to world up because then it cannot rotate upside-down
Here is the script that I've attached to the camera
using UnityEngine;
public class MainCamera : MonoBehaviour
{
Vector2 startingPosition;
Vector2 mousePosition;
Vector3 orthogonalCameraVector;
float degreesPerUnitWidth = 180f / Screen.width;
float degreesPerUnitHeight = 180f / Screen.height;
float cameraRadius = 10;
void Start()
{
transform.position = new Vector3(0, 0, -cameraRadius);
transform.LookAt(Vector3.zero);
orthogonalCameraVector = -Vector3.left;
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
mousePosition = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
var input = new Vector2(Input.mousePosition.x ,Input.mousePosition.y);
startingPosition = mousePosition;
var mouseDelta = startingPosition - input;
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
var rotation = xzRotation * yRotation;
orthogonalCameraVector = rotation * orthogonalCameraVector;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;
mousePosition = Input.mousePosition;
}
}
}
I realized the orthogonalCamerVector only needed to be rotated about the y-axis because I wanted to keep it parallel with the xz-plane. I then applied this rotation to the orthogonalCamerVector before rotating the transform so it would always be rotating about a fixed plane so it looks something like this:
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
orthogonalCameraVector = yRotation * orthogonalCameraVector;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var rotation = xzRotation * yRotation;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;

Rotate Camera vector to look at player Unity

I create a game, like minigolf/pool. I want to have a camera which follow player.
Position is normally ok, I get the ball direction and I lerp.
Rotation is almost ok. Currently, rotation by Y axis is ok, but camera look straigth forward, and don't look down to the player :
I already try many thing , quaternion angleToaxis, quarternion lookat ... but doesn't look good, the camera go look away ...
Here my code
namespace CameraManagerNameSpace
{
public class CameraManager : MonoBehaviour
{
public float cameraHeight=13f;
public PlayerNameSpace.Player playerToFollow;
public float followSpeed = 3f;
public float rotationSpeed = 1f;
float distance;
Vector3 position;
Vector3 newPos;
Quaternion rotation;
Quaternion newRot;
Vector3 playerPrevPos, playerMoveDir;
bool firstMoveDone=false;
void Start()
{
playerPrevPos = playerToFollow.player_transform.position;
distance = Vector3.Distance(transform.position,playerToFollow.player_transform.position);
}
void FixedUpdate()
{
if(Vector3.Distance(playerToFollow.player_transform.position ,playerPrevPos)>0.5f || firstMoveDone)
{
playerMoveDir = playerToFollow.player_transform.position - playerPrevPos;
firstMoveDone = true;
}
else
{
playerMoveDir = new Vector3(0,0,0);
}
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.Normalize();
newPos = playerToFollow.player_transform.position - playerMoveDir * distance;
newRot =Quaternion.LookRotation(playerMoveDir,Vector3.up);
position = Vector3.Lerp(transform.position, new Vector3(newPos.x,newPos.y+cameraHeight,newPos.z), followSpeed * Time.deltaTime);
rotation = Quaternion.Lerp(transform.rotation, newRot, rotationSpeed * Time.deltaTime);
transform.position = position;
transform.rotation = rotation;
playerPrevPos = playerToFollow.player_transform.position;
}
}
}
}
Also, I don't know why, but after the balls stop the camera continue to do some movement very jerky, jolting, halting.
Well in
newRot = Quaternion.LookRotation(playerMoveDir,Vector3.up);
you are saying the camera to look in the same direction the player is moving ... not to look at the player. This would work if you wouldn't give the camera an extra position offset in the Y axis.
You might want to rather try
// vector pointing from the camera towards the player
var targetDirection = playerToFollow.player_transform.position - transform.position;
newRot = Quaternion.LookRotation(targetDirection, Vector3.up);
You should also rather use Update since FixedUpdate is only used for physics related stuff (also see Update & FixedUpdate)

Unable to change rotation in Unity3D

I've been working on a project in Unity3D and found a javascript that makes the enemies follow the player. This is the script:
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
When the enemies "rotate to look at the player" they rotate from a horizontal position to a vertical. How can I change the script in order to prevent that from happening?
You have a secon parameter at Quaternion.LookRotation
You may use :
Quaternion.LookRotation(target.position - myTransform.position, Vector3.up)
or
Quaternion.LookRotation(target.position - myTransform.position, transform.up)

Rotate game object by clicking a button

I have an object and 2 GUI texture buttons. I want to rotate the object to the left when I press the left button and to the right while pressing the other one.
Any ideas ?
I have a script that works when I drag my object. I will post the important part:
function Start ()
{
var angles = transform.eulerAngles;
x = angles.y;
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
function LateUpdate ()
{
if (isMouseOverGuiTexture()) return;
if (target && Input.GetMouseButton(0))
{
//0.1 represents the sensitivity of the mouse
x += Input.GetAxis("Mouse X") * xSpeed *0.1; //x rotation
//y -= Input.GetAxis("Mouse Y") * ySpeed *0.1; //y rotation
//y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation = Quaternion.Euler(y, x, 0);
var position = rotation * Vector3(0.900528, 8.829305, -distance+0.49548)+ target.position;
transform.rotation = rotation;
transform.position = position;
}
}
(Question answered in the comments. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
I solved it by using the following :
var imageLeft: Texture2D; // drag the left button image here
var imageRight: Texture2D; // right button image
var speed: float = 60; // rotate speed in degrees per second
private var rotLeft = false; // object rotates left if true
private var rotRight = false; // object rotates right if true;
function OnGUI()
{
rotLeft = GUI.RepeatButton(Rect(10,10,200,200), imageLeft);
rotRight = GUI.RepeatButton(Rect(230,10,200,200), imageRight);
}
function Update()
{
if (rotLeft) transform.Rotate(0, -speed*Time.deltaTime, 0);
if (rotRight) transform.Rotate(0, speed*Time.deltaTime, 0);
}
I don't know which value Time.deltaTime assumes inside OnGUI - it should be the time since last OnGUI, but I'm not sure. To avoid problems, I placed the real rotation in Update and used two control booleans (rotLeft and rotRight) to communicate with OnGUI.