First Person Controller camera rotation doesn't work - c#

I'm looking for some c# script on unity to update first person controller
camera rotation transform. More specificly, I'm running an animation, and by the end of animation, I set "movie camera transform" on fps camera transform, how to show the code. For position variable, everything is ok. However, rotation variable doesn't work well.
The variable get the transform rotation right (the same movie camera transform), but I can't see the change on scene. The "first person controller rotation transform"
always get the last rotation coordinate that happened.
I already tested many rotation functions, like Rotate(Vector3), rotation, localRotation, eulerAngles, localEulerAngles....
Vector3 pos, roteuler;
public Camera fpscam, movie;
void getPosRot(){
roteuler = movie.transform.eulerAngles;
pos = movie.transform.position;
}
void Update(){
fps.transform.position = pos;
fps.transform.eulerAngles = roteuler;
}

Here is the camera part of my FPS script:
public class PlayerController : MonoBehaviour
{
float RotateX;
float RotateY;
public GameObject Camera;
public float RotationSpeed = 3.0f;
public float MaxYAxis = 60.0f;
public float MinYAxis = -48.0f;
private void Start()
{
}
void Update()
{
Rotation();
}
void Rotation()
{
RotateX += Input.GetAxis("Mouse X") * RotationSpeed;
RotateY += Input.GetAxis("Mouse Y") * RotationSpeed;
RotateY = Mathf.Clamp(RotateY, MinYAxis, MaxYAxis);
Camera.transform.localRotation = Quaternion.Euler(-RotateY, 0f, 0f);
transform.rotation = Quaternion.Euler(0f, RotateX, 0f);
}
}

Related

Rotate the turret and muzzle of the tank

It is necessary to rotate the turret and muzzle so that the sight is always directed to the center of the screen. I have a camera that can be rotated separately, and the turret and muzzle should follow it slowly, like in the world of tanks.
I have this code. The tower does not keep up with the camera and stops where I took the camera.
public class Tower : MonoBehaviour
{
public Transform Towr;
public Transform Cannon;
public float TowerSpeed;
public float CannonSpeed;
float TowerAngle;
float CannonAngle;
private void Update()
{
RotateTower();
RotateCannon();
}
void RotateTower()
{
TowerAngle += Input.GetAxis("Mouse X") * TowerSpeed * Time.deltaTime;
TowerAngle = Mathf.Clamp(TowerAngle, -90, 90);
Towr.localRotation = Quaternion.AngleAxis(TowerAngle, Vector3.up);
}
void RotateCannon()
{
CannonAngle += Input.GetAxis("Mouse Y") * CannonSpeed * -Time.deltaTime;
CannonAngle = Mathf.Clamp(CannonAngle, -2, 2);
Cannon.localRotation = Quaternion.AngleAxis(CannonAngle, Vector3.right);
}
}
I already found a solution how to rotate the tower behind the camera along the "Y" axis
public Transform cam;
public float speed = 50f;
private void FixedUpdate()
{
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, Quaternion.Euler(0, cam.eulerAngles.y , 0), speed * Time.deltaTime);
}

Unity mouse y-axis locked only in build

I have a mouse look script which allows the player to look up and down in a 3D first person game. It works perfectly in the Unity Editor. Once I build the game, I can only move the mouse on x-axis. I have tried using the old and new input system, but the same result happens. I have tried setting the window mode in the player settings to fullscreen and windowed already as well as setting the input system to both.
Here is a video clip of this happening: https://www.youtube.com/watch?v=_AxX2OmkU_Y
public class MouseLook : MonoBehaviour
{
Transform playerTransform;
PlayerController playerController;
InputMaster input;
Vector2 lookDir;
public float sens = 500f;
private float xRotation;
// Start is called before the first frame update
void Start()
{
// Hide cursor
Cursor.lockState = CursorLockMode.Locked;
playerTransform = transform.parent;
playerController = playerTransform.GetComponent<PlayerController>();
input = playerController.Input;
}
// Update is called once per frame
void Update()
{
lookDir = input.Player.Look.ReadValue<Vector2>();
// Gets mouse inputs
float moveX = lookDir.x * sens * Time.deltaTime;
float moveY = lookDir.y * sens * Time.deltaTime;
// Clamps rotation
xRotation -= moveY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerTransform.Rotate(Vector3.up * moveX);
}
}
I would use Input.GetAxis("MouseX") and Input.GetAxis("MouseY")
Make sure not to use Input.GetAxisRaw because it won't work as intended with mouse inputs :)
Documentation Link
Here is a example from the above link for mouse looking:
using UnityEngine;
using System.Collections;
// Performs a mouse look.
public class ExampleClass : MonoBehaviour
{
float horizontalSpeed = 2.0f;
float verticalSpeed = 2.0f;
void Update()
{
// Get the mouse delta. This is not in the range -1...1
float h = horizontalSpeed * Input.GetAxis("Mouse X");
float v = verticalSpeed * Input.GetAxis("Mouse Y");
transform.Rotate(v, h, 0);
}
}

Rotate enemy character to see player character

I am making the enemy character to follow the player character.
In the FixedUpdate method the enemy character move toward the player character,
then in the Update method character rotates to the player character.
However, with this script, somehow enemy character is just nudging and gets stuck.
Where is the mistake, what's wrong???
public class enemy : MonoBehaviour
{
GameObject tObj;
private Vector3 latestPos;
public string targetObjectName;
public float speed = (float)1.0;
void Start()
{
tObj = GameObject.Find("player");
latestPos = transform.position;
}
void Update()
{
Vector3 diff = transform.position - latestPos;
latestPos = transform.position;
if (diff.magnitude > 0.01f)
{
transform.rotation = Quaternion.LookRotation(diff);
}
}
void FixedUpdate(){
Vector3 dir = (tObj.transform.position - this.transform.position).normalized;
float vx = dir.x * speed;
float vz = dir.z * speed;
this.transform.Translate((float)(vx / 50.0),0,(float)(vz / 50.0));
}
}
Use Package Manager "Standard Assets", Inside Unity put two FPSController one should be Player and the second can be Enemy.
I know this does not answers your question but its a faster way to ad Enemy.
AI Settings
Just remove the camera, Audio Source and First Person Controller Script as in image.
The Code for AI:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowAI : MonoBehaviour
{
public CharacterController _controller;
public Transform target;
public GameObject Player;
[SerializeField]
float _moveSpeed = 2.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update() {
Vector3 direction = target.position - transform.position;
direction = direction.normalized;
Vector3 velocity = direction * _moveSpeed;
_controller.Move(velocity * Time.deltaTime);
Vector3 lookVector = Player.transform.position - transform.position;
lookVector.y = transform.position.y;
Quaternion rot = Quaternion.LookRotation(lookVector);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, 1);
}
}

Can't rotate and move at the same time

I'm currently developing an FPS shooter in Unity 3D. I'm fairly new to Unity and I've been having a bit of trouble with my player movement script. Individually everything seems to work, I can rotate and move the player freely, however when I try doing the two simultaneously my player seems to lock and won't rotate.
Sometimes jumping or moving to higher ground on the terrain seems to fix the issue, however I ran a few checks with gravity disabled, no colliders, and with the player well above ground, so the problem seems to be with the script. I've also done a bit of debugging and the Rotate() code does run, just the rotation amount doesn't seem to change.
Here is the player movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMov : MonoBehaviour
{
[SerializeField]
private Camera cam;
[SerializeField]
private float speed = 5f;
[SerializeField]
private float looksensitivity = 4f;
[Header("Camera View Lock:")]
[SerializeField] //min and max amount for looking up and down (degrees)
private float lowlock = 70f;
[SerializeField]
private float highlock = 85f;
private Rigidbody rb;
private float currentrotx; //used later for calculating relative rotation
public Vector3 velocity;
public Vector3 rotation; // rotates the player from side to side
public float camrotation; // rotates the camera up and down
public float jmpspe = 2000f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CalcMovement();
CalcRotation();
Rotate();
}
void FixedUpdate()
{
Move();
}
private void CalcRotation()
{
float yrot = Input.GetAxisRaw("Mouse X"); //around x axis
rotation = new Vector3(0f, yrot, 0f) * looksensitivity;
float xrot = Input.GetAxisRaw("Mouse Y"); //around y axis
camrotation = xrot * looksensitivity;
}
private void CalcMovement()
{
float xmov = Input.GetAxisRaw("Horizontal");
float zmov = Input.GetAxisRaw("Vertical");
Vector3 movhor = transform.right * xmov;
Vector3 movver = transform.forward * zmov;
velocity = (movhor + movver).normalized * speed;
}
void Move()
{
//move
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
//jump
if (Input.GetKeyDown(KeyCode.Space))
{
//add double jump limit later!
rb.AddForce(0, jmpspe * Time.deltaTime, 0, ForceMode.Impulse);
}
}
void Rotate()
{
//looking side to side
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
// camera looking up and down
currentrotx -= camrotation;
currentrotx = Mathf.Clamp(currentrotx, -lowlock, highlock);
cam.transform.localEulerAngles = new Vector3(currentrotx, 0, 0);
}
}
Here are the relevant components attached to my player:
(The player has a couple more components attached but I ran tests without them and the problem still occurs)
Like I said I'm a bit of a unity novice, so i'm sure I missed something small but I just can't seem to place my finger on it, I've been stuck on this for a while so any help is much appreciated.
SOLVED:
It seems the problem I had was because I was running the scene from my laptop and not a desktop which I assume is what the Unity input was built for.

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);
}
}

Categories