Problem rotating an object on its local orientation - unity3d

Hello i am new in the forum! I hope i am in the right section! Im trying to rotate a camera (that rapresent the player POV) using the mouse delta and im rotating the camera in local coordinates not world coordinates and i want avoid gimbal lock effect. I read somewhere on the internet that for that purpose i have to use quaternions, and i read how to do that. The problem is that axis rotations works well moving in local orientation but one of the axis is losing its local orientation and it rotate following the world coordinates orientation. I will post the code and i hope someone can help me and telling me where im doing things wrong. Thanks!
public class Player : MonoBehaviour {
[Header("Camera")]
[SerializeField] private Camera _camera;
[SerializeField] private Vector2 _xMinMaxRotation = new Vector2(-90, 90);
[SerializeField] private Vector2 _yMinMaxRotation = new Vector2(-90, 90);
[SerializeField] private float _mouseXSensistivity = 1;
[SerializeField] private float _mouseYSensistivity = 1;
[SerializeField] private float _mouseZSensistivity = 1;
[SerializeField] private float _xStartRotation = 0;
[SerializeField] private float _yStartRotation = 0;
private Vector2 _mouseDelta;
private float _rotY, _rotX, _rotZ;
//public GameObject head;
// Start is called before the first frame update
void Start() {
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update() {
_mouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
MoveCamera();
}
private void MoveCamera() {
_rotX += _mouseDelta.x * _mouseXSensistivity * Time.deltaTime * 100;
_rotX = Mathf.Clamp(_rotX, _xMinMaxRotation.x, _xMinMaxRotation.y);
_rotY += _mouseDelta.y * _mouseYSensistivity * Time.deltaTime * 100;
_rotY = Mathf.Clamp(_rotY, _yMinMaxRotation.x, _yMinMaxRotation.y);
//Calculation for RotZ
if (Input.GetKey(KeyCode.Q)) {
_rotZ += +_mouseZSensistivity * Time.deltaTime * 50;
if (_rotZ > 25) _rotZ = 25;
}
else {
if (_rotZ > 0) {
_rotZ -= 2 * _mouseZSensistivity * Time.deltaTime * 50;
if (_rotZ < 0) _rotZ = 0;
}
}
if (Input.GetKey(KeyCode.E)) {
_rotZ += -_mouseZSensistivity * Time.deltaTime * 50;
if (_rotZ < -25) _rotZ = -25;
}
else {
if (_rotZ < 0) {
_rotZ -= 2 * -_mouseZSensistivity * Time.deltaTime * 50;
if (_rotZ > 0) _rotZ = 0;
}
}
Quaternion currentRotation = Quaternion.identity;
currentRotation = currentRotation * Quaternion.AngleAxis(_rotX, transform.up);
currentRotation = currentRotation * Quaternion.AngleAxis(-_rotY, transform.right);
currentRotation = currentRotation * Quaternion.AngleAxis(_rotZ, transform.forward);
_camera.transform.localRotation = currentRotation;
//head.transform.position = _camera.transform.position;
//head.transform.rotation = _camera.transform.rotation;
}
The last part with quaternions is where im trying to calculate angles in order to properly rotate in local coordinates.

You don’t need to use quaternions at all.
You can use transform.EulerAngles instead of the transform.rotation or transform.localEulerAngles instead of transform.LocalRotation.
I messed up the capitalization I’m sure.
Say you wanted to rotate the camera 10 degrees along the local x axis. That would look something like
transform.localEulerAngles = transform.localEulerAngles.Add(10,0,0);
That’s it as far as I know. If you wanna read more about this,
transfrom.localEulerAngles
If your question was completely different, let me know and I can change or remove my answer.

Related

How can I get this jumping and movement code to work together?

I'm trying to use the Character Controller component in Unity and I managed to make the movement code, however, I was unable to add jumping and gravity or at least have them work together so my temporary solution was to just break them into 2 different methods. This probably isn't ideal so how could I get this to work properly?
void Update()
{
GetInput();
JumpingCode();
MovementCode();
}
void JumpingCode()
{
// Jumping
if (jumpPressed && characterController.isGrounded)
velocityY = Mathf.Sqrt(jumpHeight * -2f * (gravity * gravityScale));
// Gravity
velocityY += gravity * gravityScale * Time.deltaTime;
Vector3 direction = new Vector3(horizontalInput, velocityY, verticalInput).normalized;
characterController.Move(direction * walkSpeed * Time.deltaTime);
}
void MovementCode()
{
Vector3 direction = new Vector3(horizontalInput, 0f, verticalInput).normalized;
if (direction.magnitude > 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + playerCamera.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
transform.rotation = Quaternion.Euler(0f, angle, 0f);
characterController.Move(moveDirection.normalized * walkSpeed * Time.deltaTime);
}
}
I can't understand how you're arriving at the values you're using there, but the solution would be to accumulate the outputs and then do the .Move() action once at the end, like:
void Update()
{
Vector3 motion;
GetInput();
motion += JumpingCode();
motion += MovementCode();
characterController.Move(motion*Time.deltaTime);
}
private Vector3 JumpingCode()
{
// stuff
return direction * walkSpeed;
}
private Vector3 MovementCode()
{
// stuff
return direction * walkSpeed;
}
Noteworthy there is that I dropped Time.deltaTime from your functions, but I don't know how you were using it in the code you provided.

Problem with blend tree when float return 0 in unity 2019.4.1f1

I have a problem with blend tree which I'm using it and a script to change the float so I can control the player's animation. But the value of the parameter in the blend tree went crazy when it return to 0. It start appearing random numbers and the only way I know to fix it is to reset it manually.
This is what happen after hitting 0 -->
what happen.gif
Is it there way I use the blend tree wrong or a new bug in unity?. Any ideas??
AnimationController
animationController.jpg
ThirdPersonCharacterController
public float walkSpeed = 2;
public float runSpeed = 6;
public float gravity = -12;
public float jumpHeight = 1;
public float airControlPercent;
public float turnSmoothTime = 0.2f;
float turnSmoothVelocity;
public float speedSmoothTime = 0.1f;
float speedSmoothVelocity;
float currentSpeed;
float velocityY;
Animator animator;
Transform cameraT;
CharacterController controller;
void Start () {
animator = GetComponent<Animator> ();
cameraT = Camera.main.transform;
controller = GetComponent<CharacterController> ();
}
void Update () {
// input
Vector2 input = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
Vector2 inputDir = input.normalized;
bool running = Input.GetKey (KeyCode.LeftShift);
Move (inputDir, running);
if (Input.GetKeyDown (KeyCode.Space)) {
Jump ();
}
// animator
float animationSpeedPercent = ((running) ? currentSpeed / runSpeed : currentSpeed / walkSpeed * .5f);
animator.SetFloat ("speedPercent", animationSpeedPercent, speedSmoothTime, Time.deltaTime);
}
void Move(Vector2 inputDir, bool running) {
if (inputDir != Vector2.zero) {
float targetRotation = Mathf.Atan2 (inputDir.x, inputDir.y) * Mathf.Rad2Deg + cameraT.eulerAngles.y;
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetRotation, ref turnSmoothVelocity, GetModifiedSmoothTime(turnSmoothTime));
}
float targetSpeed = ((running) ? runSpeed : walkSpeed) * inputDir.magnitude;
currentSpeed = Mathf.SmoothDamp (currentSpeed, targetSpeed, ref speedSmoothVelocity, GetModifiedSmoothTime(speedSmoothTime));
velocityY += Time.deltaTime * gravity;
Vector3 velocity = transform.forward * currentSpeed + Vector3.up * velocityY;
controller.Move (velocity * Time.deltaTime);
currentSpeed = new Vector2 (controller.velocity.x, controller.velocity.z).magnitude;
if (controller.isGrounded) {
velocityY = 0;
}
}
void Jump() {
if (controller.isGrounded) {
float jumpVelocity = Mathf.Sqrt (-2 * gravity * jumpHeight);
velocityY = jumpVelocity;
}
}
float GetModifiedSmoothTime(float smoothTime) {
if (controller.isGrounded) {
return smoothTime;
}
if (airControlPercent == 0) {
return float.MaxValue;
}
return smoothTime / airControlPercent;
}
Note: the parameter for the blend tree is "speedPercent"
I am not sure but i think that the value you are seeing is so near to zero that it has gone to exponential form as Unity always does for smaller values like
And this is because you are using smooth transition for SetFloat
animator.SetFloat ("speedPercent", animationSpeedPercent,
speedSmoothTime, Time.deltaTime);
Try this
animator.SetFloat ("speedPercent", animationSpeedPercent);

Write IEnumerator for Movement

I want to write an IEnumerator to move at the desire distance at a specified time. I have tried to write the code for this but this is running a different way.
float moveDistance=1f;
float moveSpeed=5f;
float elapsedDistance = 0f;
while (elapsedDistance <= moveDistance)
{
elapsedDistance += Time.deltaTime * moveSpeed;
Vector3 cubeLocalPosition = transform.localPosition;
cubeLocalPosition.y += Time.deltaTime * moveDistance;
transform.localPosition = cubeLocalPosition;
yield return null;
}
Through this code, Object can't able to travel 1 unit distance. How can I correct this code?
Your while loop condition uses elapsedDistance which is increasing with moveSpeed. That latter is 5 so it will be 1 in 1/5 of a second. Your object is likely only moving 0.2unit.
you should use Mathf.Lerp or MoveTowards
float distance = 1f;
float time = 0f;
float period = 1f; // how long in second to do the whole movement
yield return new WaitUntil(()=>
{
time += Time.deltaTime / period;
float movement = Mathf.Lerp(0f, distance, time);
Vector3 cubeLocalPosition = transform.localPosition;
cubeLocalPosition.y += movement;
transform.localPosition = cubeLocalPosition;
return time >= 1f;
});
Following your own rotation, you calculate the finalpoint to go
and after,
you could use Vector3.Lerp or Vector.Slerp to move in the specified time..So the moving speed adapt itself following the time desired
var endpoint = transform.position + transform.forward.normalized * distance;
StartCoroutine(MoveToPosition(transform, endpoint, 3f)
:
:
public IEnumerator MoveToPosition(Transform transform, Vector3 positionToGO, float timeToMove)
{
var currentPos = transform.position;
var t = 0f;
while (t < 1f)
{
t += Time.deltaTime / timeToMove;
transform.position = Vector3.Lerp(currentPos, positionToGO, t);
yield return null;
}
transform.position = positionToGO;
}

Single object 3D viewer for Google Cardboard with Unity 5

I'm trying to recreate the functionality of the Google Cardboard app’s 'Exhibit' demo. i.e. viewing a single object from all sides - look up and you see under the object, look down and you view it from above, look left or right and you see it from the side, then back.
I've tried a number of things like making the object a child of the camera, and using transform.LookAt(target); to keep the camera focused on the object but it isn't working.
New to Unity5 so any help would be very much appreciated.
UPDATE
Using code from a SmoothMouseLook script (http://pastebin.com/vMFkZJAm) this is the closest I've got so far, but it doesn't really work and feels too 'out of control' (the object keeps spinning rather than smoothly turning for inspection) and much less predictable than the 'Exhibit' demo. My guess is that I'm over complicating things. Anyone have any ideas?...
On the Camera(s) ("Main Camera") attach this to keep focused on the object:
using UnityEngine;
using System.Collections;
public class LookAt : MonoBehaviour {
public Transform target;
void Update () {
transform.LookAt(target);
}
}
On the Object, attach this script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SmoothMouseLook : MonoBehaviour
{
/*
This script is used to average the mouse input over x
amount of frames in order to create a smooth mouselook.
*/
//Mouse look sensitivity
public float sensitivityX = 1f;
public float sensitivityY = 1f;
//Default mouse sensitivity
public float defaultSensX = 1f;
public float defaultSensY = 1f;
//Minimum angle you can look up
public float minimumY = -60f;
public float maximumY = 60f;
//Minimum angle you can look up
public float minimumX = -60f;
public float maximumX = 60f;
//Number of frames to be averaged, used for smoothing mouselook
public int frameCounterX = 35;
public int frameCounterY = 35;
//Mouse rotation input
private float rotationX = 0f;
private float rotationY = 0f;
//Used to calculate the rotation of this object
private Quaternion xQuaternion;
private Quaternion yQuaternion;
private Quaternion originalRotation;
//Array of rotations to be averaged
private List<float> rotArrayX = new List<float> ();
private List<float> rotArrayY = new List<float> ();
void Start ()
{
//Lock/Hide cursor
if (GetComponent<Rigidbody>())
GetComponent<Rigidbody>().freezeRotation = true;
originalRotation = transform.localRotation;
}
void FixedUpdate ()
{
//Mouse/Camera Movement Smoothing:
//Average rotationX for smooth mouselook
float rotAverageX = 0f;
//rotationX += Camera.main.transform.eulerAngles.x * sensitivityX;
//rotationX += Cardboard.SDK.HeadRotation.eulerAngles.x * sensitivityX;
rotationX += Cardboard.SDK.HeadPose.Orientation.x * sensitivityX;
rotationX = ClampAngle (rotationX, minimumX, maximumX);
//Add the current rotation to the array, at the last position
rotArrayX.Add (rotationX);
//Reached max number of steps? Remove the oldest rotation from the array
if (rotArrayX.Count >= frameCounterX) {
rotArrayX.RemoveAt (0);
}
//Add all of these rotations together
for (int i_counterX = 0; i_counterX < rotArrayX.Count; i_counterX++) {
//Loop through the array
rotAverageX += rotArrayX[i_counterX];
}
//Now divide by the number of rotations by the number of elements to get the average
rotAverageX /= rotArrayX.Count;
//Average rotationY, same process as above
float rotAverageY = 0;
//rotationY += Camera.main.transform.eulerAngles.y * sensitivityY;
//rotationY += Cardboard.SDK.HeadRotation.eulerAngles.y * sensitivityY;
rotationY += Cardboard.SDK.HeadPose.Orientation.y * sensitivityY;
rotationY = ClampAngle (rotationY, minimumY, maximumY);
rotArrayY.Add (rotationY);
if (rotArrayY.Count >= frameCounterY) {
rotArrayY.RemoveAt (0);
}
for (int i_counterY = 0; i_counterY < rotArrayY.Count; i_counterY++) {
rotAverageY += rotArrayY[i_counterY];
}
rotAverageY /= rotArrayY.Count;
//Apply and rotate this object
xQuaternion = Quaternion.AngleAxis (rotAverageX, Vector3.up);
yQuaternion = Quaternion.AngleAxis (rotAverageY, Vector3.left);
transform.localRotation = originalRotation * xQuaternion * yQuaternion;
}
private float ClampAngle (float angle, float min, float max)
{
if (angle < -360f)
angle += 360f;
if (angle > 360f)
angle -= 360f;
return Mathf.Clamp (angle, min, max);
}
}
For that particular use case, you don't need a script. Assuming you are using the CardboardMain prefab, do this:
Put the object at the origin, and the CardboardMain there too.
In the Cardboard settings, set Neck Model Scale to 0.
Open up CardboardMain and select Main Camera under the Head object.
Set it's Transform Position Z value to a negative value (far enough to see the object).
(You can think of this as the "selfie-stick" camera model.)

Unity Smooth 2D Camera following - Huge Issue :(

As you can see in the topic - I have a camera problem. I use a script (you can see below) and I have something like this - http://rapidgamesstudio.com/games/diggermachines/
What I want to achieve is a smooth following camera to player.
I've tried everything. I have about 50-60 fps and still this bug occures.
This is my camera code:
void Update() {
if(!player)
return;
//if(!isDiggableCamera) {
Vector3 point = Camera.main.WorldToViewportPoint(player.transform.position);
Vector3 delta = player.transform.position - Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
Vector3 destination = transform.position + delta;
destination.z = transform.position.z;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
//Vector3 destination = new Vector3(player.transform.position.x, player.transform.position.y, transform.position.z);
//transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
//} else {
// startDigging(0, 0, 0);
//}
leftSite.position = new Vector3(leftSite.position.x, player.position.y, leftSite.position.z);
rightSite.position = new Vector3(rightSite.position.x,
player.position.y, rightSite.position.z);
}
I tried execute this code in Update(), FixedUpdate(), LateUpdate() even with all three - and still is the same problem.
Below code for updating player position:
//move player
float changableSpeedX = 5000.0f;
float changableSpeedY = 6000.0f;
Vector2 speed = new Vector2(x * Time.deltaTime * changableSpeedX,
y * Time.deltaTime * changableSpeedY);
//if(playerRigidbody.velocity.y + speed.y >= Game.game().activeMaxVelY)
// speed.y = Game.game().activeMaxVelY - playerRigidbody.velocity.y;
playerRigidbody.AddForce(speed);
//AddForce(speed);
//and checking max speed
protected void checkSpeed()
{
if(playerRigidbody.velocity.x > Game.game().activeMaxVelX)
playerRigidbody.velocity = new Vector2(Game.game().activeMaxVelX, playerRigidbody.velocity.y);
if(playerRigidbody.velocity.x < -Game.game().activeMaxVelX)
playerRigidbody.velocity = new Vector2(-Game.game().activeMaxVelX, playerRigidbody.velocity.y);
if(playerRigidbody.velocity.y > Game.game().activeMaxVelY)
playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, Game.game().activeMaxVelY);
if(playerRigidbody.velocity.y < maxSpeedYGravity)
playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, maxSpeedYGravity);
}
Could anyone help me?
If you need more code please let me know which part (because I don't want to add too much unnecessary code)
Might i suggest a lerp sir , in the update function use this
maincamera.transform.position = new vector3(maincamera.transform.position,player.transform.poistion,speed*Time.deltaTime);
Try This One !!!
private float xMax;
[SerializeField]
private float yMax;
[SerializeField]
private float xMin;
[SerializeField]
private float yMin;
private Transform target;
// Use this for initialization
void Start () {
target = GameObject.Find("Player").transform;
}
// Update is called once per frame
void LateUpdate () {
transform.position = new Vector3(Mathf.Clamp(target.position.x, xMin, xMax), Mathf.Clamp(target.position.y, yMin, yMax),transform.position.z);
}
}