Unity C# How to turn item in hands when player turns - c#

I am pretty new to unity but i have a basic FPS game made, when holding a gun, i would like to make it so when your player turns, the item in hands rotates to show turning. For example, when playing call of duty, the gun rotates when you rotate your character. This is the code i have but it is not working
void Update(){
this.rotateEquppedOnTurn();
}
private void rotateEquppedOnTurn(){
if(this.equippedItem != null){
InteractEquppableItem equip = this.equippedItem.gameObject.GetComponent<Interaction>() as InteractEquppableItem;
if(equip.rotatesWhenTurn){
float rotX = Input.GetAxis("Mouse X");
float rotY = Input.GetAxis("Mouse Y");
Quaternion tempRot = new Quaternion();
Quaternion tempCam = GameObject.Find("PlayerCamera").transform.rotation;
tempRot.x = tempCam.x + rotX;
tempRot.y = tempCam.y + rotY;
tempRot.z = tempCam.z;
this.equippedItem.gameObject.transform.rotation = tempRot;
}
}
}
when turning the character with this code, the gun just rotates in a weird way, its not quite what i expected from the rotation script

Quaternions are not vectors.
I suggest you start by watching the vector tutorial on Unity's web site.
The last bit of the tutorial goes over what cross products are and why you would use them - specifically, you can use them to obtain a relative axis around which you may want to rotate something.

Don't directly assign rotation like this.
this.equippedItem.gameObject.transform.rotation = tempRot;
instead of that use something like this
this.equippedItem.gameObject.transform.Rotate(new Vector3(x,y,z));
you can derive x,y,z using mouse motion

Related

Look Relative Movement in Unity using Cinemachine

I'm relatively new to coding, having just started about a week ago, and I can't seem to figure out or find anything relating to look relative movement using a third person Cinemachine freelook camera.
What I'm trying to accomplish is a camera similar to Risk of Rain 2, or maybe Smite where you can orbit the player and look at the front of them while they're idle, but once you start moving the player rotates towards the direction the camera is looking, and stays facing that direction no matter how they're moving.
I have a basic scene set up with a Cinemachine freelook camera following a cube, but my problem is whenever I turn the camera then move, my character doesn't rotate and instead starts moving in the direction it's facing instead of where the camera's looking, then only starts rotating if I'm pressing a movement key, so the rotation gets disjointed from where the camera's looking, if that makes sense. I kind of frankensteined some code from Royal Skies' movement tutorial and someone else's rotation tutorial for a top-down game.
This is the code for a script applied to my player character;
public float speed = 4.5f;
public Vector3 deltaMove;
public float turnspeed = 500;
void Update()
{
deltaMove = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime; //movement code
transform.Translate(deltaMove);
float horizontal = Input.GetAxis("Mouse X");
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D) == true) //if wasd pressed, rotate
{
transform.Rotate(horizontal * turnspeed * Vector3.up * Time.deltaTime, Space.World); //the rotation code
}
}
I'd be willing to do anything to be honest, I've been trying to figure this out for a bit now.

How to make camera relative movement

I'm learning unity and c#, and want to make my movement to be camera relative movement instead of world relative movement. How do I do that?
I'm learning unity and c#, my unity version is 2018.3.12f1. I would be happy for help.
just to let know, instead of moving the cam I'm rotating the player.
void Update()
{
float AxisY = Player.transform.eulerAngles.y;
/* Movement starts here */
Vector3 Movement = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { //running code
Player.transform.position += Movement * running_speed * Time.deltaTime;
} else {
Player.transform.position += Movement * speed * Time.deltaTime;
}
/*Movement ends here */
/* Rotation controller starts here */
Quaternion target = Quaternion.Euler(Player.transform.eulerAngles.x, Player.transform.eulerAngles.y, Player.transform.eulerAngles.z);
/*if (Player.transform.eulerAngles.x != 0 || Player.transform.eulerAngles.z != 0 || Player.transform.eulerAngles.y != 0) {
Player.transform.rotation = Quaternion.Euler(0,0,0);
}*/
if (Input.GetKey(KeyCode.E))
{
Debug.Log("E got pressed");
//float AxisYPositive = Player.transform.eulerAngles.y;
AxisY = AxisY+1;
Player.transform.rotation = Quaternion.Euler(0, AxisY, 0);
} else if (Input.GetKey(KeyCode.Q))
{
Debug.Log("Q got pressed");
//float AxisYNegetive = Player.transform.eulerAngles.y;
AxisY=AxisY-1;
Player.transform.rotation = Quaternion.Euler(0, AxisY, 0);
}
}
}
The player's movement is world relative, how to make the movement camera relative?
If you want to make the movements relative to the gameObject, call the method Transform.Rotate() on the transform of the gameObject you want to rotate rather than modifying its Quaternion directly. Just make sure the final argument is set to Space.Self.
if (Input.GetKey(KeyCode.E))
{
Debug.Log("E got pressed");
//float AxisYPositive = Player.transform.eulerAngles.y;
AxisY = AxisY+1;
Player.transform.Rotate(Quaternion.Euler(0, AxisY, 0), Space.Self);
}
In general you don't want to directly mess with objects transform.rotation, at least not unless you at least somewhat understand quaternions (I don't!).
I can see a few issues with your code, but the common thread seems to be that you don't really understand how transforms work. Specifically, you might want to look into World/Local space.
The usual way to control a player goes roughly like this:
void DoMovement(Transform player)
{
//If you move first your controls might feel 'drifty', especially at low FPS.
Turn(player);
Move(player);
}
void Turn(Transform player)
{
float yaw = Input.GetAxis("Yaw") * time.deltaTime; //Aka turn left/right
player.Rotate(0, yaw, 0, Space.Self);
// Space.Self is the default value, but I put it here for clarity.
//That means the player will rotate relative to themselves,
//...instead of relative to the world-axis, like in your code.
}
You didn't ask about movement, but as-is your character will always move relative to the world. The below should make it move relative to the camera.
Transform _cameraTransform; //Assumes this is set druing Start()
void Move(Transform player)
{
var forwardMove = _cameraTransform.Forward; //Get whatever direction is 'forward' for camera
forwardMove.Y = 0; //Don't want movement up and down.
forwardMove = forwardMove.normalized; //Normalize sets the 'power' of the vector to 1.
//If you set Y to 0 and don't normalize you'll go slower when camera looks down
//...than when camera is flat along the plane
player.position += forwardMove * Input.GetAxis("Vertical") * time.deltaTime;
//Here you could do the same for strafe/side to side movement.
//Would be same as above, but using the transform.right and Horizontal axis
}
Now, I'm making some assumptions here since you haven't specified what kind of game it is and what kind of controls you want. I'm assuming you have a character running around on a mostly flat plane (no aircraft/spaceship controls), and that the camera is attached to the player. This might not not actually be the case.
In any case I advice you to check out the tutorials, especially the Roll-a-Ball tutorial which I have found is good for beginners to get a grasp on basic players controls that are not just world-relative. The other tutorials, too, are pretty good if you think they're interesting.
Aside from the official Unity tuts a ton of decent to amazing tutorials out there, including video tutorials, so for something like this you could just search for <game type> tutorial and pick whatever seems good to you. While getting started I advice you to avoid the shortest videos, as you will likely benefit greatly from explanation that only fits in longer videos. Of course, that doesn't mean you should pick the longest videos either.
In case someone needs to move an object and don't care about colliders, you can use transform.Translate and assign to his second parameter relativeTo your camera (or any transform) to automatically calculate the translation relative to the object assigned.

I have no syntax errors in Unity, How can I find errors so I learn why my crosshair stays in the center of the screen?

For Unity Game: shouldn't the cross-hair move accordingly as the player rig does to point at enemies? how can I find error with no syntax error messages?
I tried visiting Unity forums I found support about raycasting followed directions add some code to the crosshair.cs script I receive no syntax errors.
public class CrossHair: MonoBehaviour{
[SerializeField] private GameObject standardCross;
[SerializeField] private GameObject redCross;
float moveForce = 1.0f;
float rotateTorque = 1.0f;
float hoverHeight = 4.0f;
float hoverForce = 5.0f;
float hoverDamp = 0.5f;
Rigidbody rb;
private RaycastHit raycastHit;
void Start()
{
standardCross.gameObject.SetActive(true);
rb = GetComponent<Rigidbody>();
// Fairly high drag makes the object easier to control.
rb.drag = 0.5f;
rb.angularDrag = 0.5f;
}
void Update()
{
// Push/turn the object based on arrow key input.
rb.AddForce(Input.GetAxis("Vertical") * moveForce * transform.forward);
rb.AddTorque(Input.GetAxis("Horizontal") * rotateTorque * Vector3.up);
RaycastHit hit;
Ray downRay = new Ray(transform.position, -Vector3.up)
if (Physics.Raycast(downRay, out hit))
{
//The "error" in height is the difference between the desired height
// and the height measured by the raycast distance.
float hoverError = hoverHeight - hit.distance;
// Only apply a lifting force if the object is too low (ie, let
// gravity pull it downward if it is too high).
if (hoverError > 0)
{
// Subtract the damping from the lifting force and apply it to
// the rigidbody.
float upwardSpeed = rb.velocity.y;
float lift = hoverError * hoverForce - upwardSpeed * hoverDamp;
rb.AddForce(lift * Vector3.up);
}
}
Ray targettingRay = new Ray(transform.position, transform.forward)
if (Physics.Raycast(targettingRay, out raycastHit, 100))
{
if (raycastHit.transform.tag == "Enemies")
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
redCross.gameObject.SetActive(true);
standardCross.gameObject.SetActive(false);
}
}
else
{
redCross.gameObject.SetActive(false);
standardCross.gameObject.SetActive(true);
}
}
}
I except for the crosshair in my game to follow the player rig camera as the code explains. Any guidance is appreciated.
Syntax errors are those kind of errors which prevent your game/program from running at all. They are like grammar mistakes that need to be fixed before you can run your code.
A syntax error is your pc telling you:
I can't run this because I don't understand this. or I can't run this because this is not allowed.
One example would be int x = "Hello World". This in not allowed because I can not assign an string value to an integer (like that).
But your code not having any syntax errors does not mean it will do what you intended it for, it just means your code will run.
A good and easy way of debugging your code in Unity is to add Debug.Log("My Log Message"); statements to your code where you think it would be beneficial. These are going to be logged to your console output in Unity while you are in play mode. You can for example do something like this to constantly get your cross's position and rotation logged:
Debug.Log("Cross Position: " + standardCross.transform.position);
Debug.Log("Cross Rotation: " + standardCross.transform.rotation);
Just be sure to remove them once you are done with them because having Debug.Logs in your code takes as significant hit to your performance.
Another, more sophisticated way of debugging your code is through the usage of breakpoints in Visual Studio or whatever IDE/Editor you are using.
It basically comes down to declaring points where your program should pause execution for you to look at values in your program itself.
It's quite handy but goes above and beyond what I could tell you via this text, so please have a look at this Unity-specific use case: Debugging Unity games with Visual Studio
Now to your code:
First: There is a Vector3.down so you don't have to use -Vector3.up.
Second: Do you need a GameObject as crosshair? Why not just add a UI-Crosshair instead?
That way it always stays in the middle of your screen wherever you turn your camera.
Just add a new Image to your UI via GameObject -> UI -> Image, give it some kind of crosshair look in the inspector and lock it to the middle of the screen by left-clicking on the little crosshair in the top left of the Inspector while you have your Image selected and then Shift + Alt + Left click the middle option.
If you really want to use a separate gameObject as crosshair then maybe attatch it to your player object as a child. That way it will move and rotate with your player automatically and you do not have to do this via script.
Hope this helps!

Rotate player with platform without parenting

I'm currently making a small platformer 3D game, but unfortunately I can't make the player to rotate properly when it is riding the platform, the thing here is that I don't want to make the player child of the platform, so far I've managed to make him move smoothly along with the platform, but the rotation is still going nowhere, here is the code I'm using for the rotation:
player.transform.rotation *= platform.rotation;
and here is the effect I got:
Rotation Error
not very nice :(
I guess the solution is something simple, some formula, but unfortunately I'm not very good with math :( So, thank you guys, I hope you can help me.
I'll show you a simple script example which makes a cube rotate by input while reacting to the rotation of the platform on which it stands:
using UnityEngine;
public class CubeRotation : MonoBehaviour {
public GameObject Platform;
Quaternion PreviousPlatformRotation;
public float rotationSpeed = 50;
private void Start() {
PreviousPlatformRotation = Platform.transform.rotation;
}
private void Update() {
//Rotate the cube by input
if (Input.GetKey(KeyCode.A)) {
transform.Rotate(Vector3.up, Time.deltaTime * rotationSpeed);
}
if (Input.GetKey(KeyCode.D)) {
transform.Rotate(Vector3.up, -Time.deltaTime * rotationSpeed);
}
//Adjust rotation due to platform rotating
if (Platform.transform.rotation != PreviousPlatformRotation) {
var platformRotatedBy = Platform.transform.rotation * Quaternion.Inverse(PreviousPlatformRotation);
transform.rotation *= platformRotatedBy;
PreviousPlatformRotation = Platform.transform.rotation;
}
}
}
The logic of the adjustment to the platform rotation is this:
Get at start the rotation quaternion of the platform (in your case, get it when the cube object climbs on the platform)
With A and D rotate the cube normally around the local Y axis.
Afterwards check if the platform's rotation has changed, if yes:
3.a Get how much the platform rotated since the previous frame, with the operation Actual rotation * Inverse(Previous Rotation); this operation it's akin to a difference between two quaternions
3.b Add that quaternion to the cube's rotation with the *= operator
3.c Set the platform's previous rotation value to the new one.
That's pretty much it.

AI Car Unity wrong rotation

This is my first post, so if I do something wrong, let me know it. Im doing in Unity 5.5 a 2D Car Game, with a topdown view. For the game, i need that some cars have a simple AI Script, just for follow a path. So, I searched in the web something that fits my needs, and found(in my opinion) a really good implementation. Here i let u the project in GitHub, uploaded by the owner of the implementation I suppose: https://github.com/mindcandy/lu-racer
So in a few words, we create a Path with empty GameObjects and the respective colliders, we have to have a car(obviously) and set up with a collider and a rigidbody2d, and we have three scripts that "do the magic". For my project, I remove the part of counting the laps because my game is not a race. Well, i set up all and everything works fine! Except for one thing: the carĀ“s rotation.
I think this is happens because the tutorial game is a topdown view but cars go from left to right, and in my game is topdown also but cars go from down to up. So the cars's sprites in my project are in topdown view and looking to up, and the car's sprite of the github project are topdown view looking to right(i wanted upload the images but appears me that i cant do it due my reputation, sorry).
Definitely, the AI works really good and the car follow without problems the path, but with a wrong rotation, like this: aicar_rotation
I tried changing things in the AICarMovement scripts related to the vectors, and angles, but without luck, so if anyone can look and give me a hand, I'll be grateful. If anyone wants more details for understand the problem, let me know. I try upload more things like pictures or gifs to show the problem, but i cant do it due the reputation.
This is the part of code in AICarMovement that i think i have to change:
public class AICarMovement : MonoBehaviour {
public float acceleration = 0.5f;
public float braking = 0.3f;
public float steering = 4.0f;
private Rigidbody2D rigidb;
Vector3 target;
void Start() {
rigidb = GetComponent<Rigidbody2D>();
}
public void OnNextTrigger(TrackLapTrigger next){
target = Vector3.Lerp(next.transform.position - next.transform.right, next.transform.position + next.transform.right, Random.value);
}
void steerTowardsTarget() {
Vector2 towarNextTrigger = target - transform.position;
float targetRot = Vector2.Angle(Vector2.right, towarNextTrigger);
if(towarNextTrigger.y < 0.0f) {
targetRot = -targetRot;
}
float rot = Mathf.MoveTowardsAngle(transform.localEulerAngles.z, targetRot, steering);
transform.eulerAngles = new Vector3(0.0f, 0.0f, rot);
}
void FixedUpdate(){
steerTowardsTarget();
float velocity = rigidb.velocity.magnitude;
velocity += acceleration;
rigidb.velocity = transform.right * velocity;
rigidb.angularVelocity = 0.0f;
}
}
Sorry about my english, is not my native language.
Turn your sprite and also the spawn game object. This way you have no fancy behaviour and all looks correct.
In steerTowardsTarget(), 2nd line:
Try to change the first parameter of Angle() from Vector2.right to Vector2.up.

Categories