Unknown rotation behaviour of gameObject while trying to rotate using LocalEulerAngles - c#

I am new to game development , I am following a book Unity in action by Manning . This is the code snippet used to rotate a game object (from the book):
public RotationAxes axes = RotationAxes.MouseXandY;
public float sensitivityHorizontal = 9.0f;
public float sensitivityVert = 9.0f;
private float rotationX = 0;
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
// Update is called once per frame
void Update () {
float input = Input.GetAxis ("Mouse X");
//Vertical Rotation
if (axes == RotationAxes.MouseY) {
rotationX-= Input.GetAxis ("Mouse Y") * sensitivityVert;
rotationX = Mathf.Clamp (rotationX, minimumVert, maximumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3 (rotationX, rotationY, 0);
}
}
This code actually works but the other way around i.e when my move my mouse upwards the object rotates down and up when I move down . I figured out that it was rotationX-= Input.GetAxis ("Mouse Y") * sensitivityVert; this that was causing the problem so I change it to rotationX+= Input.GetAxis ("Mouse Y") * sensitivityVert; and now it rotates really strangely ! I have made sure that it only rotates in vertical axis but it's rotating in all the directions i.e even in horizontal and z axis.
Can somebody please tell me where I am going wrong? ThankYou

Works fine for me. I cleaned up your code and constrained Y to its initial value.
public class rotateX : MonoBehaviour
{
public float sensitivityVert = 9.0f;
private float rotationX = 0;
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
Vector3 initial;
void Start()
{
initial = transform.localEulerAngles;
}
// OnMouseDown is called when the user has pressed the
// mouse button while over the GUIElement or Collider.
protected void OnMouseDown()
{
sign = -sign;
}
float sign = -1f;
void Update()
{
rotationX += sign * Input.GetAxis("Mouse Y") * sensitivityVert;
//rotationX = Mathf.Clamp(rotationX, minimumVert, maximumVert);
transform.localEulerAngles = new Vector3(rotationX, initial.y, 0f);
}
}
The cube rotates up and down around its pivot.

Related

moving with wasd with the camera in unity

I'm a new programmer and I was following some tutorial on YouTube but I am having difficulty making it work.
Here's the error I get:
NullReferenceException: Object reference not set to an instance of an object
Moving.Update () (at Assets/Moving.cs:39)
Here's the code:
public class Moving : MonoBehaviour
{
public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;
private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis
public GameObject player;
public CharacterController controller;
public float speed = 6f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Vector3 rot = transform.localRotation.eulerAngles;
rotY = rot.y;
rotX = rot.x;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");
rotY += mouseX * mouseSensitivity * Time.deltaTime;
rotX += mouseY * mouseSensitivity * Time.deltaTime;
rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);
Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
transform.rotation = localRotation;
transform.parent.transform.Rotation = Quaternion.Euler(rotX, rotY, 0.0f);
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 Direction = (player.transform.forward * vertical + player.transform.right * horizontal).normalized;
controller.Move(Direction * speed * Time.deltaTime);
}
}
I'm using unity 2020.3.37
You haven't provided all the code so I can't exactly know which line is 39 but I think you are getting this error because your transform doesn't have a parent so this line is causing the error.
transform.parent.transform.Rotation = Quaternion.Euler(rotX, rotY, 0.0f);
So first make sure you have assigned the values for player and controller in the inspector then make sure either your object with Moving.cs attached to it have a parent or try remove or change the line of code that is trying to get the transform.parent.

How to make the player walk in the direction it is pointing?

I made a simple movement system in Unity 3D, but I don't know how to make it so that I move in the direction my player is pointing in.
using UnityEngine;
public class PlayerControler : MonoBehaviour
{
CharacterController characterController;
public float MovementSpeed = 1f;
public float Gravity = 9.8f;
private float velocity = 0f;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal") * MovementSpeed;
float vertical = Input.GetAxis("Vertical") * MovementSpeed;
characterController.Move((Vector3.right * horizontal + Vector3.forward * vertical) * Time.deltaTime);
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
}
}
This is the player controller.
using UnityEngine;
public class MouseControl : MonoBehaviour
{
public float horizontalSpeed = 1f;
public float verticalSpeed = 1f;
private float xRotation = 0.0f;
private float yRotation = 0.0f;
private Camera cam;
void Start()
{
cam = Camera.main;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * horizontalSpeed;
float mouseY = Input.GetAxis("Mouse Y") * verticalSpeed;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f);
}
}
This is the code that makes my character face where my cursor is.
Edit: This is a First-Person 3D game. The player has a CharacterControler component on it, and the Main Camera is a child of the player. The second piece of code changes the direction that the camera is facing when the cursor is moved. The first script is the movement script, and utilises the CharacterController component of the player to move. I want to make to that instead of going in four static directions every time I press a movement key, I want the player to move in proportion to the direction that the camera is facing (on the X axis). E.g: If I am facing West and I press “W” to go forwards, I want the character to go West instead of North.
Instead of the global vectors Vector3.forward and Vector3.right in
characterController.Move((Vector3.right * horizontal + Vector3.forward * vertical) * Time.deltaTime);
rather use your local direction vectors Transform.forward and Transform.right
characterController.Move((transform.right * horizontal + transform.forward * vertical) * Time.deltaTime);
#derHugo was right, but I forgot to update the angles in the player movement script, so it always thought that I was rotated 0,0,0.
using UnityEngine;
public class PlayerControler : MonoBehaviour
{
Vector3 angles;
CharacterController characterController;
MouseControl mouseControl;
public float MovementSpeed = 1f;
public float Gravity = 9.8f;
private float velocity = 0f;
void Start()
{
characterController = GetComponent<CharacterController>();
mouseControl = GetComponent<MouseControl>();
}
void Update()
{
angles = new Vector3(mouseControl.xRotation, mouseControl.yRotation, 0f);
transform.eulerAngles = angles;
float horizontal = Input.GetAxis("Horizontal") * MovementSpeed;
float vertical = Input.GetAxis("Vertical") * MovementSpeed;
characterController.Move((transform.right * horizontal + transform.forward * vertical) * Time.deltaTime);
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
}
}
Updated code
Note: I had to made the X and Y rotation variables public.
[HideInInspector]public float xRotation = 0.0f;
[HideInInspector]public float yRotation = 0.0f;

Rotate Camera when touch unity 3d

Here it is. I have a human anatomy, and I would like to rotate the camera when I touch anywhere. but looking at the human anatomy. how can I do that :(
[https://www.youtube.com/watch?v=EfYeL2FYyyA&t=148s] this is what exactly I really wanted to please help me !
`
using UnityEngine;
using System.Collections;
[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour {
public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float distanceMin = .5f;
public float distanceMax = 15f;
private Rigidbody rigidbody;
float x = 0.0f;
float y = 0.0f;
// Use this for initialization
void Start ()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x; rigidbody = GetComponent<Rigidbody>();
// Make the rigid body not change rotation
if (rigidbody != null)
{
rigidbody.freezeRotation = true;
}
}
void LateUpdate ()
{
if (target)
{
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);
RaycastHit hit;
if (Physics.Linecast (target.position, transform.position, out hit))
{
distance -= hit.distance;
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}}
You could use a trick instead of using too many "math" in this case.
There will be empty gameObjects in each of the element you want your camera to rotate around, lets call those "anchors"
When the element is selected, you simply make the camera child of the anchor.
And then if you just rotate the anchor, your camera will rotate because it is the child.
This will get the effect you want.
Here is a simple example from youtube, for rotating the object.
Here is another one from Unity answers.
Hope this helps! Cheers!

3d mouse aim camera 3rd person vertical C#

I'm trying to make mouse aim camera that rotate my Player horizontally and vertically, look at Player and keep constant distance.
In that version it works fine but I can't make it horizontal also.
Each version camera freezes and I rotate my player itself or so.
I'm new to programming so I it's propably easy task with proper target.transform.eulerAngles.y assigning also to vertical but I cannot do it.
public class MouseAimCamera : MonoBehaviour {
public GameObject target;
public float rotateSpeed = 5;
Vector3 offset;
void Start() {
offset = target.transform.position - transform.position;
}
void LateUpdate() {
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
target.transform.Rotate(0, horizontal, 0);
float desiredAngle = target.transform.eulerAngles.y;
Quaternion rotation = Quaternion.Euler(0, desiredAngle, 0);
transform.position = target.transform.position - (rotation * offset);
transform.LookAt(target.transform);
}
}
I'd be glad if any of you can help me.
This will rotate in world space, which will probably feel wrong at some angles since the camera is not always oriented straight up.
public class MouseAimCamera : MonoBehaviour {
public GameObject target;
public float rotateSpeed = 5;
void Start() {
transform.parent = target.transform;
transform.LookAt(target.transform);
}
void LateUpdate() {
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
target.transform.RotateAround(target.transform.position, Vector3.up, horizontal);
target.transform.RotateAround(target.transform.position, Vector3.left, vertical);
}
}
This will rotate in local space, and might feel more natural depending on what you're trying to build. This is close to your original solution, so i'm guessing it's not what you want.
public class MouseAimCamera : MonoBehaviour {
public GameObject target;
public float rotateSpeed = 5;
void Start() {
transform.parent = target.transform;
transform.LookAt(target.transform);
}
void LateUpdate() {
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
target.transform.Rotate(vertical, horizontal, 0);
}
}

Mathf.clamp is not working correctly

I have made my own character in Unity, I'm working on the camera right now and I want to clamp the Y rotation of the Camera, while I'm doing this the correct way.
mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f);
So what just happens is that the camera is rotating from 359 to 0. Nothing happens until I move my mouse up when playing the game. It makes the screen look like it's flickering.
Here's my full code:
using UnityEngine;
using System.Collections;
public class FirstPersonController : MonoBehaviour {
CharacterController cc;
public float baseSpeed = 3.0f;
public float mouseSensitivity = 1.0f;
float mouseRotX = 0,
mouseRotY = 0;
public bool inverted = false;
float curSpeed = 3.0f;
string h = "Horizontal";
string v = "Vertical";
void Start () {
cc = gameObject.GetComponent<CharacterController>();
}
void FixedUpdate () {
curSpeed = baseSpeed;
mouseRotX = Input.GetAxis("Mouse X") * mouseSensitivity;
mouseRotY -= Input.GetAxis("Mouse Y") * mouseSensitivity;;
mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f);
if (!inverted)
mouseRotY *= -1;
else
mouseRotY *= 1;
float forwardMovement = Input.GetAxis(v);
float strafeMovement = Input.GetAxis(h);
Vector3 speed = new Vector3(strafeMovement * curSpeed, 0, forwardMovement * curSpeed);
speed = transform.rotation * speed;
cc.SimpleMove(speed);
transform.Rotate(0, mouseRotX, 0);
Camera.main.transform.localRotation = Quaternion.Euler(mouseRotY, 0 ,0);
}
}
If anyone of you could help me with this, that would be splendid. Thanks.
Your inverted logic is flawed, just take it out and it works. To invert the rotation you need to invert only the input and not the rotation itself every frame(it will just go from + to - and back to + again and so on). Here is a stripped down version for the y-rotation with inverted flag that works:
using UnityEngine;
using System.Collections;
public class FirstPersonController : MonoBehaviour
{
public float mouseSensitivity = 1.0f;
float mouseRotY = 0.0f;
public bool inverted = false;
private float invertedCorrection = 1.0f;
void FixedUpdate ()
{
if(Input.GetAxis ("Fire1") > 0.0f)
inverted = !inverted;
if(inverted)
invertedCorrection = -1.0f;
else
invertedCorrection = 1.0f;
mouseRotY -= invertedCorrection * Input.GetAxis("Mouse Y") * mouseSensitivity;
mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f);
Camera.main.transform.localRotation = Quaternion.Euler(mouseRotY, 0.0f, 0.0f);
}
}
another thing you might want to do is get the original rotation of the camera in your Start() function. The way it is now it sets the rotation to zero on the first frame. I cant tell from the script if this is the intended behaviour or not.

Categories