I'm making a third person game and when I try to makie the character (cube) face the way the players mouse is pointing my character just goes flying off even though I didn't use W, A, S or D?
public class FollowPlayer : MonoBehaviour
{
public Transform player;
public Vector3 CamPosition;
public Transform PlayerBody;
public float MouseSensitivity = 100f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float MouseX = Input.GetAxis("Mouse X") * MouseSensitivity * Time.deltaTime;
float MouseY = Input.GetAxis("Mouse Y") * MouseSensitivity * Time.deltaTime;
PlayerBody.Rotate(Vector3.up * MouseX);
transform.position = player.position + CamPosition;
}
}
Did you attach it to the player or the cam?
See if you have a rigidbody attached to the player, it may be buggy due to the way they work in relation with transforms.
Try to mark the line that rotates the player. I believe it's somewhere else that causes the problem because there is nothing in there that moves the player.
Reply me if you found anything that affects the movement.
Related
Hello again my friends.
I am trying to make a 3D game in Unity in which I am trying to move my character with simple WASD keys.
However, it is successful only from one direction. From the opposite direction the controls seem reversed. Even when I look around with the mouse. The game is considered to be a First-Person Shooter(FPS).
The Player code is:
[SerializeField]
private NavMeshAgent navMeshAgent;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector3 direction = new Vector3(Input.GetAxis("Horizontal1"), 0, Input.GetAxis("Vertical1"));
Vector3 velocity = direction * speed;
velocity.y -= gravity;
velocity = transform.TransformDirection(velocity);
controller.Move(direction * Time.deltaTime);
transform.position = navMeshAgent.nextPosition;
}
What should I do? I would really appreciate your help.
Try this example to move your character use your own logic ofc and change what have to be changed
private float speed = 2.0f;
public GameObject character;
void Update () {
if (Input.GetKeyDown(d)){
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKeyDown(a)){
transform.position += Vector3.left* speed * Time.deltaTime;
}
if (Input.GetKeyDown(w)){
transform.position += Vector3.forward * speed * Time.deltaTime;
}
if (Input.GetKeyDown(s)){
transform.position += Vector3.back* speed * Time.deltaTime;
}
}
I have a unity scene with a character holding a weapon. The weapon is a child of the camera and so moves with the camera allowing the player to aim the weapon. My issue is that the 3d model of the character has hands which i wish to be holding on to the weapon. Initially, to get past this issue, I used IK's to place the hands on the gun, this worked but didn't allow me to aim the gun as it would be fixed to the hands. How would I go about keeping the hands attached to the weapon whilst still being able to aim?
The player look script is attached for refrence:
public float sensitivityX = 5.0f;
public float sensitivityY = 5.0f;
public int Limits = 80;
public Transform playerBody;
float xRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * sensitivityX * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * sensitivityY * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, (Limits * -1), Limits);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
If anymore information is needed please let me know, thank you.
FIX:
Parent gun to hand, use animation rigging IK's to follow a target (I used multi aim constraints), do this for both the hand and the spine. Set the source object as a sphere, either disable it from being visible in the camera or just make it very small, then make it a child of the camera, place it at X=0, Y=0 and Z=>0.
Ive been trying to add recoil to my fps game (Used Brackeys tutorials for the base), but the camera looking script is causing the rotation to be set each frame. I cant figure out how to change the camera rotation without the script resetting it
Code for the looking script is attatched below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 1500f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
To change the camera rotation without the script resetting it I would use an if statement to check if a different rotation should be applied ex:
bool canLook = true;
if(canLook == false) {
//apply your desired rotation
}
else
{
//run your looking code
}
//When you want to apply your rotation set canLook to false
//And when you want to return to the camera movement set canLook to true
I am making code for a first person physics-based character controller in Unity. The movement is mostly smooth, but when I go up a slope, instead of sliding back down, the character floats in the air slightly while slowly moving downward until it gets back to the ground. This behavior is very strange and unexpected, and I don't really know why this is happening.
The character is an empty object with a capsule and a sphere childed to it. The script is on the empty object, and the rigidbody is on the capsule which is a child to the empty.
Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
float mouseSensitivity;
private float cameraXRotation;
private float cameraYRotation;
private float movementX;
private float movementY;
private Transform playerHeadTransform;
private Transform playerBodyTransform;
private Rigidbody playerRigidBody;
private bool IsJumping;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
playerBodyTransform = transform.GetChild(0).gameObject.GetComponent<Transform>();
playerHeadTransform = transform.GetChild(0).transform.GetChild(0).gameObject.GetComponent<Transform>();
playerRigidBody = transform.GetChild(0).gameObject.GetComponent<Rigidbody>();
playerHeadTransform.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
mouseSensitivity = 750;
IsJumping = false;
}
// Update is called once per frame
void Update()
{
#region CameraStuff
float cameraMouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float cameraMouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
cameraXRotation -= cameraMouseY;
cameraYRotation += cameraMouseX;
cameraXRotation = Mathf.Clamp(cameraXRotation, -90f, 60);
playerHeadTransform.localRotation = Quaternion.Euler(cameraXRotation, 0f, 0f);
playerBodyTransform.localRotation = Quaternion.Euler(0f, cameraYRotation, 0f);
#endregion
//Movement input variables
movementX = Input.GetAxis("Horizontal") * mouseSensitivity * Time.deltaTime;
movementY = Input.GetAxis("Vertical") * mouseSensitivity * Time.deltaTime;
}
void FixedUpdate()
{
playerRigidBody.velocity = playerBodyTransform.TransformDirection(movementX*2, 0, movementY*2);
}
}
Your player not falling down is most probably related to you setting
void FixedUpdate()
{
playerRigidBody.velocity = playerBodyTransform.TransformDirection(movementX*2, 0, movementY*2);
}
if there is gravity involved you rather want to make sure to not overwrite the Y axis and do e.g.
var currentVelocity = playerRigidbody.velocity;
var newVelocity = playerBodyTransform.TransformDirection(movementX * 2, 0, movementY * 2);
// keep the velocity on Y but only if it is currently downwards
// so you can still move up on a slope but fall down with gravity
if(currentVelocity.y < 0) newVelocity.y = currentVelocity.y;
playerRigidBody.velocity = newVelocity;
In my game I have a camera and I want to have an FPS like rotation attached to this camera.
So if I move my cursor to the left, I want my cam to rotate to the left. If I move my cursor up, then the cam should look up, etc.
I currently have it partially working. I can look left and right, up, and down. The problem occurs when I look down and then move my cursor left and right. It then gives me a "Roll" effect.
See this video to see exactly what I mean:
http://www.screencast.com/t/Phedh8H0K13
Obviously when I look down I still want to have a "Yaw" effect instead of a "Roll" effect. Anyone any idea how to do that? This is what I have so far:
// Update is called once per frame
public override void update ()
{
this.camera.transform.rotation *=
Quaternion.AngleAxis( Time.deltaTime * sensitivityRoll * Input.GetAxis("Vertical"), Vector3.forward );
this.camera.transform.rotation *=
Quaternion.AngleAxis( Time.deltaTime * sensitivityYaw * Input.GetAxis("Mouse X"), Vector3.up );
this.camera.transform.rotation *=
Quaternion.AngleAxis( Time.deltaTime * sensitivityPitch * Input.GetAxis("Mouse Y"), Vector3.left );
}
I just found my answer in this topic:
http://forum.unity3d.com/threads/109250-Looking-with-the-Mouse?highlight=person+camera
The code from that topic:
C# Mono code:
using UnityEngine;
using System.Collections;
/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation
/// To make an FPS style character:
/// - Create a capsule.
/// - Add the MouseLook script to the capsule.
/// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSInputController script to the capsule
/// -> A CharacterMotor and a CharacterController component will be automatically added.
/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
/// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
float rotationY = 0F;
void Update ()
{
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
void Start ()
{
//if(!networkView.isMine)
//enabled = false;
// Make the rigid body not change rotation
//if (rigidbody)
//rigidbody.freezeRotation = true;
}
}
Simple Script, Not Sure it will work with you, might as well give it a try
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;
public class mouse_lookat : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
using UnityEngine;
public class CameraRotator : MonoBehaviour
{
[SerializeField] private Transform _head;
[SerializeField] private float _sensitivity;
[SerializeField] private bool _invertVertical;
private void Update()
{
var deltaMouse = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y");
Vector2 deltaRotation = deltaMouse * _sensitivity;
deltaRotation.y *= _invertVertical ? 1.0f : -1.0f;
float pitchAngle = _head.localEulerAngles.x;
// turns 270 deg into -90, etc
if (pitchAngle > 180)
pitchAngle -= 360;
pitchAngle = Mathf.Clamp(pitchAngle + deltaRotation.y, -90.0f, 90.0f);
transform.Rotate(Vector3.up, deltaRotation.x);
_head.localRotation = Quaternion.Euler(pitchAngle, 0.0f, 0.0f);
}
}
i created 2 scripts for my FPS project that work flawlessly for my movement (currently havnt added jump mechanics) and it seems like youve overcomplicated alot of things that can be quite simple and straight forward.
im also new to coding so please correct me if im wrong heres my code
// this is in the player script which i put on an empty parent object of the camera and player sprite
public class player : MonoBehaviour
{
[Header("player Movement")]
[SerializeField] float moveSpeed = 5f;
[SerializeField] public float mouseSensitivity = 5f;
Rigidbody rigidBody;
// Use this for initialization
void Start()
{
}
void Update()
{
Move();
}
private void Move()
{
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime);
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime);
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * mouseSensitivity);
}
//this is the camera movement script which i put on the camera(will also use this script to add a function to change from 1st person to 3rd person for certain abilities)
{
player player;
// Use this for initialization
void Start()
{
player = FindObjectOfType<player>();
}
// Update is called once per frame
void Update()
{
MoveView();
}
private void MoveView()
{
transform.Rotate(Vector3.left * Input.GetAxis("Mouse Y") * player.mouseSensitivity);
}
}