Rotate a Rigidbody on X axis based on mouse movement - c#

My Player object consists of a playermodel itself and an empty GameObject "FollowTarget".
FollowTarget has a script attached to it, which makes the camera rotate along with it; Cinemachine is also made to follow it.
So essentialy, the camera itself works well and follows the player around just as intended.
But I also need my player to rotate around the X axis along with rotating the camera.
I am currently using this code to rotate the player around X axis:
rb.MoveRotation(rb.rotation * Quaternion.Euler(new Vector3(0, mouseX * 200f * Time.fixedDeltaTime, 0)));
This works, but makes the mouse rotation on X axis rough, unpolished, uneven - something like that. On FollowTarget I use a simple code to get mouse input:
mouseX += Input.GetAxis("Mouse X") * mouseSens;
mouseY += Input.GetAxis("Mouse Y") * mouseSens;
mouseY = Mathf.Clamp(mouseY, minAngleY, maxAngleY);
transform.localRotation = Quaternion.Euler(-mouseY, 0, 0);
Not adding mouseX to this code, because the previous one already reads mouseX, but as I said, it makes the X rotation rough and it feels weird to rotate the camera in-game. When I add mouseX to this code the player doesn't rotate as intended. Using mouseX only in this code obviously makes the player not rotate at all.
So how can I combine it? How can I make the camera move through FollowTarget, and also make my Rigidbody playermodel rotate on X axis based on mouse input? Tried many different solutions, combinations, code examples and checked many different posts and nothing worked for me.

Related

How to make an object move straight from random directions in Unity

I have a ball object in Unity 2D, this ball spawns at random positions on the screen and I want it to move in a 'straight-line depending on its direction e.g. if it's from the left it goes to the right or if it's from the top it goes to the bottom. I'm not sure if I should use transform.position/addforce/velocity to accomplish this and what direction I should use.
The following are what I have tried so far (I've tried using all directions)
ballRigidBody.AddForce(transform.up * speed);
ballRigidBody.velocity = Vector2.up * speed;
transform.position+=Vector2.up;
In Unity3D transform.forward is the go to variable when you want to move forward.
In Unity2D transform.right is the standard.
You can move your ball to its right with this code:
void Update()
{
GetComponent<Rigidbody2D>().velocity = transform.right * speed;
}
If you run this code the ball will always move into the direction of the red arrow.
You can see the arrows by selecting the move tool on the top left and then clicking on your ball inside the editor.
If you want to have your ball to always follow the green arrow you have to use transform.up.
transform.right and transform.up are both used relative to your object.
That means by changing the z rotation of your object you can modify the direction it should go in.
You can try out the following code to see your ball move to its right and rotate slowly on its z axis. This will cause the ball to move in a circle since it is still following the red arrow.
void Update()
{
GetComponent<Rigidbody2D>().velocity = transform.right * speed;
float speedRotate = 100;
transform.Rotate(Vector3.forward * speedRotate * Time.deltaTime);
}
When you always want to move an object to the right, no matter the rotation, you use Vector3.right instead of transform.right.
From your other comments I understand that you want your ball to always face into the direction in the middle of the screen. You can just rotate it to the middle of the screen when it spawns by using this code:
void Start()
{
transform.right = new Vector3(0, 0, 0) - transform.position;
}
This will get the ball to face the 0,0,0 position inside of your world. If 0,0,0 is in the middle of your screen it will face that direction. Otherwise you have to find out which coordinate your middle of your screen has.
I'm not sure what you're asking, but you can do ballRigidbody.velocity = transform.foward*speed, to make it go in the current direction it is facing.
If you want a ball you spawn on the left side of the screen to move to the right only, then set velocity like rb.velocity = Vector3.right * speed, and so on with each direction.
In this case, you should first check which position the ball spawned at (Top, Bottom, Left, Right), then from that decide the movement direction. If the ball spawns at the bottom, the direction to go up should be Vector3.up for example.
After you get the force, you can use rigidBody.AddForce(direction * speed); to move the ball.

How to lock the camera on X and Z axis, even though it is locked to a cube's rotation?

When the cube moves in the space, the camera follows it, because I made the camera a child of the cube. When the cube rotates in the Y direction (using player input), the camera does too. That is expected.
However, when the cube falls off a plane (it has rigid body physics), it rotates because of gravity (which is something I want), but the camera does too, because they are linked. How can I make the camera stuck in the X and Z directions?
This is how I control the cube's rotation:
float h = rotationSpeed * Input.GetAxis("Mouse X");
transform.Rotate(0, h, 0);

Arrow rotating to face cursor needs to only do so while inside an angle made by two given directions

I have a 2d arrow rotating to always face the a target (the target in this case is the cursor), the pivot is my player character. I need to restrict this arrow to only follow the target if it is inside an angle of the player, an example would be 90 degrees, so it would only follow if the cursor is in the top right part of the screen.
I have worked with vector directions and methods such as Vector2D.angle, but they all seem to have some restriction i can't workaround, Vector2D.angles restriction is that the 3rd position it uses to calculate the angle is the world center(0, 0), my player is mobile so that doesn't work.
So i think what im asking is if theres a way to store an angle, and then check if something is within that.
Here is the code i use for rotating my arrow, theres more to the script but i removed the unnecesary parts:
public float speed;
public Transform target;
void Update()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = target.position - transform.position;
target.position = mousePosition;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
Sorry if this is formatted poorly, its my first time posting here, thank you a million times if you are able to help me, i have been stuck on this for days.
Was asked to clarify question so here is an attempt:
This picture shows an example of what i mean, the arrow is rotating around the center of the circle, (it is rotating so it always points towards my cursor). What i need is a way to restrict it so it only points towards the cursor if it is within a specific angle (red lines in picture), that's what im having trouble with. I can't find a way to store this threshold and i can't seem to find a way to compare the cursors direction with it.
I think it would be possible if it was possible to choose a custom center for Vector2D.angle, but that doesn't seem to be the case.
I hope this clarifies what my question, i may just very well be stupid and overlooking something obvious but i really can't find a way to make this possible.
thanks again.
Important fields/inputs
First, we need to know the boundary directions in world space:
public Vector2 boundaryDirectionLeft;
public Vector2 boundaryDirectionRight;
The important piece is that the angle made clockwise from boundaryDirectionLeft to boundaryDirectionRight is the region the arrow shall remain inside. In the case of your image, boundaryDirectionLeft could be Vector2.up and boundaryDirectionRight could be something like new Vector2(1f,-1f).
We also need to know which local direction the arrow is facing before any rotation is applied. E.g., if the arrow is always pointing with the local red arrow axis (the local right direction), this would be Vector2.right:
public Vector2 localArrowDirection;
And lastly, we need a top speed for our rotation, so we don't warp the arrow around when it's time to rotate. A good value to start with might be 360f, 360 degrees per second. Try experimenting with different values to find one that you like:
public float maxRotationSpeed;
The update procedure
In Update, determine the direction to the target:
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - transform.position;
Then, we need to know where the arrow is currently pointing. We can use Transform.TransformVector to find where the local localArrowDirection is pointing in world space:
Vector2 currentDirection = transform.TransformVector(localArrowDirection);
Then, determine the signed angle from boundaryDirectionLeft to the target direction, the same from boundaryDirectionLeft to boundaryDirectionRight, and the same from boundaryDirectionLeft to the current facing direction:
float directionAngle = Vector2.SignedAngle(boundaryDirectionLeft, direction);
float boundaryAngle = Vector2.SignedAngle(boundaryDirectionLeft, boundaryDirectionRight);
float currentAngle = Vector2.SignedAngle(boundaryDirectionLeft, currentDirection);
These values range from [-180,180], but we want them expressed in the range [0,360) to make the math easier later, so we can add 360f and use Mathf.Repeat on that sum:
directionAngle = Mathf.Repeat(directionAngle+360f, 360f);
boundaryAngle = Mathf.Repeat(boundaryAngle+360f, 360f);
currentAngle = Mathf.Repeat(currentAngle+360f, 360f);
At this point directionAngle is how many clockwise degrees from boundaryDirectionLeft that target is, and boundaryAngle is how many boundaryDirectionRight is, and currentAngle is the same for what direction we're currently facing.
So, now, we need to know how to properly clamp the angle between 0 and boundaryAngle. Anything too far above boundaryAngle is actually closer to the left boundary and should be clamped to the left boundary. In fact, since everything is between 0 and 360, anything higher than boundaryAngle+(360f-boundaryAngle)/2f is closer to the left. So, we just set anything higher than that to be 0 degrees away from boundaryDirectionLeft:
if (directionAngle > boundaryAngle + (360f - boundaryAngle)/2f)
{
directionAngle = 0f;
}
So, now we can clamp directionAngle with a high of boundaryAngle (it is already bottom clamped at 0f, so we can use Mathf.Min here):
directionAngle = Mathf.Min(directionAngle, boundaryAngle);
Now we can limit the angular difference between directionAngle and currentAngle using our maxRotationSpeed:
float deltaAngle = Mathf.Clamp(directionAngle-currentAngle,
-maxRotationSpeed * Time.deltaTime,
maxRotationSpeed * Time.deltaTime);
Now we can rotate the transform deltaAngle degrees clockwise (in world space):
transform.Rotate(0f,0f,deltaAngle,Space.World);

Changing the x and y rotation weirdly changes the z too in Unity

I tried to make a first person controller in Unity so that I know every single detail of it. I made the movement, but when I created the camera rotation i simply got stuck. Ok, it worked on the x axis, on the y axis, but why does the z axis also change?
void Update () {
transform.position = Character.transform.position + offset;
float h = Input.GetAxis("Mouse X") * horizontalSpeed;
float v = Input.GetAxis("Mouse Y") * verticalSpeed;
transform.Rotate(h, v, 0, Space.World);
}
When working with rotations and euler angles you have to understand that there are different coordinate spaces, like the object's local space and a world space. the x,y,z directions in world space will always look at the same direction, whereas the local space is the coordinate space of the local object (for example your camera). Thats why I would recommend you to rotate vertically in local space and horizontally in world space.
transform.Rotate(0,h,0,Space.World);
transform.Rotate(-v, 0, 0, Space.Self);
Rotating your camera vertical in local space will change the object's local up axis (y-axis). this is why then rotating around that axis will give you your unwanted result. Just select the gameobject in your Scene view and observe it's local coordinate system while rotating and you might be able to better visually understand.
To also give you a simple,fun reallife example to observe yourself, sit upright on your office chair and look straight ahead and rotate on your chair. If you now look a little upwards or downwards and rotate your head instead you will notice a difference in rotation between rotating your neck and rotating on your chair, which should always have the same up-axis, which is different from the local up axis of your neck.
ps.: there are already many solutions to implement a first person camera, like in Unity's own standard assets, or SmoothMouseLook
Looking at tutorials, following them and trying to understand them might bring you further than trying to figure it out on your own.
Euler angles are weird. When you rotate with euler angles, the rotations stack, and a rotation around one axis changes the other axis of rotation. It's best not to "add" euler angles (essentially what transform.Rotate() is doing) and best to work with them in absolute terms. In this case, your code should keep the "z axis" at 0 if you do the following:
void Update () {
transform.position = Character.transform.position + offset;
float h = Input.GetAxis("Mouse X") * horizontalSpeed;
float v = Input.GetAxis("Mouse Y") * verticalSpeed;
# Get the current euler angle in absolute terms
Vector3 eulers = Character.transform.localEulerAngles;
# now modify that euler angle, creating a new absolute euler angle
eulers.x += h;
eulers.y += v;
eulers.z = 0;
# and now assign the new euler angle back to the transform, overwriting the old value
Character.transform.localEulerAngles = eulers;
}
In general I'd advise against using Transform.Rotate() for... most everything. I would also advise using quaternions wherever you're able. You don't need a complete understanding of quaternions for them to be very powerful.

Limited head turning with mouse in Unity 2d

I'm Using Unity 2d and I made it so that the camera turned with the mouse in the x axis no problem. But I want the camera to only turn a small amount. The mouse needs to have full freedom to move but the camera needs to stop at a certain point.
I tried making an empty game object and set it so if the camera position equals that gameobject position the camera would move slightly back but that resulted in a lot if camera clipping. Also tried altering speed but of course that doesn't work. Does anyone know how I can do this without camera clipping?
Sorry for the lack of code as my computer has no interest access. Currently my code basically is:
transform.position = newvector3.Movetowards(
Input.GetAxisRaw("mouse X") * speed * Time.DeltaTime,
0f,
Input.GetAxisRaw("mouse Y") * 0 * Time.DeltaTime
);
That might be a bit inaccurate but that's the basic of it
To prevent clipping while using limited camera movement try something like this
transform.position = new vector 3(Mathf.Clamp(transform.position.x, MIN_X, MAX_X), 0, 0);
Of course replace MIN_X and MAX_X with the numbers of the minimum and maximum position you want the camera to be able to rotate to. This is off the top of my head so the code might not be 100 percent accurate. You can find Mathf.Clamp in the Unity docs if you're having trouble.

Categories