Unity 3D character prefab not rotating as a whole - c#

I am learning Unity, 3d free look camera and no errors, the only problem is the face and hands of the character doesn't rotate, only the armor of the character is rotating when I go to a different direction. I am using a free viking prefab from unity asset store as game character, the prefab has two child the face&hands and the armor. On the line "child = transform.GetChild(0).transform;" when I replace the 0 with 1 only the face and hands rotate. How can I make the whole prefab rotate when moving around?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Player playerInput;
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
[SerializeField]
private float playerSpeed = 2.0f;
[SerializeField]
private float jumpHeight = 1.0f;
[SerializeField]
private float gravityValue = -9.81f;
[SerializeField]
private float rotationSpeed = 4f;
private Transform cameraMain;
private Transform child;
private void Awake()
{
playerInput= new Player();
controller= GetComponent<CharacterController>();
}
private void OnEnable()
{
playerInput.Enable();
}
private void OnDisable()
{
playerInput.Disable();
}
private void Start()
{
cameraMain = Camera.main.transform;
child = transform.GetChild(0).transform;
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector2 movementInput= playerInput.PlayerMain.Move.ReadValue<Vector2>();
Vector3 move = (cameraMain.forward * movementInput.y + cameraMain.right *
movementInput.x);
move.y = 0f;
controller.Move(move * Time.deltaTime * playerSpeed);
// Changes the height position of the player..
if (playerInput.PlayerMain.Jump.triggered && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
if (movementInput != Vector2.zero)
{
Quaternion rotation = Quaternion.Euler(new Vector3(child.localEulerAngles.x,
cameraMain.localEulerAngles.y, child.localEulerAngles.z));
child.rotation = Quaternion.Lerp(child.rotation, rotation, Time.deltaTime *
rotationSpeed);
}
}
}

Related

Cant change transform.position player on Unity

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class teleporttospawn : MonoBehaviour
{
public GameObject player; /// player
public Transform fps; /// also player
private void OnTriggerEnter(Collider other)
{
Debug.Log("teleport succes.");
fps.transform.position = new Vector3(-3.82f, 1.08f, -1.69f); // DONT WORK
player.transform.position = new Vector3(-3.82f, 1.08f, -1.69f); //DONT WORK
}
}
I have two players in the script above because I tried to move it in two ways but nothing worked
So I tried to set the object to vector3 and try to move the player to the object, so nothing comes out
I need teleport player when he triger the collider. Debug.Log work but transform.position dont work.
Its dosent work from this script -> fpscontroller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fpscontroller : MonoBehaviour
{
public float walkingSpeed = 7.5f;
public float runningSpeed = 11.5f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
public Camera playerCamera;
public float lookSpeed = 2.0f;
public float lookXLimit = 45.0f;
CharacterController characterController;
Vector3 moveDirection = Vector3.zero;
float rotationX = 0;
[HideInInspector]
public bool canMove = true;
public GameObject tp;
private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.CompareTag("tp"))
{
while(transform.position != tp.transform.position)
{
Debug.Log("teleport succes.");
gameObject.transform.position = tp.transform.position;
}
}
}
void Start()
{
transform.position = gameObject.transform.position;
characterController = GetComponent<CharacterController>();
// Lock cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
// We are grounded, so recalculate move direction based on axes
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
// Press Left Shift to run
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Horizontal") : 0;
float movementDirectionY = moveDirection.y;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);
if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpSpeed;
}
else
{
moveDirection.y = movementDirectionY;
}
// Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
// when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
// as an acceleration (ms^-2)
if (!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
// Move the controller
characterController.Move(moveDirection * Time.deltaTime);
// Player and Camera rotation
if (canMove)
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
}
}

Jittering movement Unity C# follow script

I'm creating a simple movement/following script in C#. I have a prefab (ball) spawn randomly within the Awake() method, at a random area in my scene. I then have another script attached to a different game object (robot) that at the start of the game shall move towards the ball.
Now the movement works but when the game object has come into the the minDistanceToTarget it begins to "jitter" and move around.
Here's the movement script:
public class RobotMovement : MonoBehaviour {
// Movement
private Transform target;
private float speed = 2f;
private float distance;
private float minDistanceToTarget = 1f;
// Rotation
private Vector3 targetDirection;
private Quaternion lookAtRotation;
private float RotationSpeed = 2f;
void Start() {
target = GameObject.FindGameObjectWithTag("Ball").transform;
}
void Update() {
targetDirection = target.position - transform.position;
lookAtRotation = Quaternion.LookRotation(targetDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, lookAtRotation, RotationSpeed * Time.deltaTime);
distance = Vector3.Distance(transform.position, target.position);
if (distance >= minDistanceToTarget) {
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
}
Edit I tried to change the affect to use FixedUpdate and affect the RigidBodies instead.
public class RobotMovement : MonoBehaviour {
private Rigidbody robot;
public Rigidbody target;
// Movement
private float speed = 2f;
private float minDistanceToTarget = 2f;
void Start() {
robot = GetComponent<Rigidbody>();
target = target.GetComponent<Rigidbody>();
}
void FixedUpdate() {
if (Vector3.Distance(robot.position, target.position) > minDistanceToTarget) {
robot.MovePosition(target.position * speed * Time.deltaTime);
}
}
}
Edit I now use a new movement method and include a rotation calculation. But it still jumps and jitters
public class RobotMovement : MonoBehaviour {
private Rigidbody robot;
private Transform ball;
// Movement
private float robotMovSpeed = 2f;
private float distanceToTarget;
private float distanceToStop = 2f;
// Rotation
private Vector3 targetDirection;
private Quaternion lookAtTarget;
private float rotationSpeed = 2f;
void Start() {
robot = GetComponent<Rigidbody>();
ball = GameObject.FindGameObjectWithTag("Ball").transform;
}
void FollowTarget(Transform target, float distanceToStop, float speed) {
distanceToTarget = Vector3.Distance(robot.position, target.position);
// Rotation
targetDirection = target.position - robot.position;
lookAtTarget = Quaternion.LookRotation(targetDirection);
if (distanceToTarget >= distanceToStop) {
transform.rotation = Quaternion.Slerp(transform.rotation, lookAtTarget, rotationSpeed * Time.deltaTime);
robot.MovePosition(robot.position + (target.position - robot.position).normalized * speed * Time.deltaTime);
}
}
void FixedUpdate() {
FollowTarget(ball, distanceToStop, robotMovSpeed);
}
}

Unity jump script delay

Im making a 3d game in unity, and so I made a cs script for movement of my charecter, walking and moveing the camera works fine, however when i added the jump function, it had a delay. You could press the jump button 5 times, with no result. Then you press it again, and it jumps. I cant figure out why this does this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController characterController;
public int speed = 6;
public float gravity = 9.87f;
private float verticalspeed = 0;
private Vector3 moveDirection = Vector3.zero;
public Transform Camera;
public float Sensitivity = 2f;
public float uplimit = -50;
public float downlimit = -50;
public float jumpspeed = 5.0f;
void Update()
{
move();
cameramove();
void cameramove()
{
float horizontal = Input.GetAxis("Mouse X");
float vertical = Input.GetAxis("Mouse Y");
transform.Rotate(0, horizontal * Sensitivity, 0);
Camera.Rotate(-vertical * Sensitivity, 0, 0);
Vector3 currentRotation = Camera.localEulerAngles;
if (currentRotation.x > 180) currentRotation.x -= 360;
currentRotation.x = Mathf.Clamp(currentRotation.x, uplimit, downlimit);
Camera.localRotation = Quaternion.Euler(currentRotation);
}
void move()
{
float horizontalMove = Input.GetAxis("Horizontal");
float verticalMove = Input.GetAxis("Vertical");
if (characterController.isGrounded) verticalspeed = 0;
else verticalspeed -= gravity * Time.deltaTime;
Vector3 gravityMove = new Vector3(0, verticalspeed, 0);
Vector3 move = transform.forward * verticalMove + transform.right * horizontalMove;
characterController.Move(speed * Time.deltaTime * move + gravityMove * Time.deltaTime);
if (characterController.isGrounded && Input.GetButton("Jump"))
{
moveDirection.y = jumpspeed;
}
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
}
}
}
Assuming your character has a RigidBody assigned to it, you can refer it on your script as,
public class PlayerMovement : MonoBehaviour
{
private Rigidbody myrigidbody;
void Start () {
myrigidbody = GetComponent<Rigidbody>();
}
}
Then you can pass the jumpspeed as a Vector3, and probably you might have to trigger your animation here as well.
if (characterController.isGrounded && Input.GetButton("Jump"))
{
characterController.isGrounded = false;
myrigidbody.AddForce(new Vector3(0, jumpspeed, 0));
// Trigger your animation, myanimator.SetTrigger("jump");
}
Unity character controller move documentation also contains jump function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// Changes the height position of the player..
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}

Unity forward position = camera angle

Hi I am very new to Unity and only got basic knowledge. I created a player who can move and also a camera which follows the player and according to the mouseX and mouseY acis the camera rotates.
Now I want the camera rotation angle to be the forward position.
If the player press w he moves along x acis but if the camera angle change and the player press w it should move into this direction.
player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoublePlayer : MonoBehaviour
{
private CharacterController _controller;
public float _jumpHeight = 3f;
[SerializeField]
private float _moveSpeed = 5f;
[SerializeField]
private float _gravity = 9.81f;
private float _directionY;
void Start()
{
_controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontalInput, 0, verticalInput);
// set gravity
_directionY -= _gravity * Time.deltaTime;
direction.y = _directionY;
_controller.Move(direction * _moveSpeed * Time.deltaTime);
}
}
camera.cs
public class CameraController : MonoBehaviour
{
public float RotationSpeed = 1;
public Transform Target, Player;
float mouseX, mouseY;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void LateUpdate()
{
CamControl();
}
void CamControl()
{
mouseX += Input.GetAxis("Mouse X") * RotationSpeed;
mouseY += Input.GetAxis("Mouse Y") * RotationSpeed;
mouseY = Mathf.Clamp(mouseY, -35, 60);
transform.LookAt(Target);
Target.rotation = Quaternion.Euler(mouseY, mouseX, 0);
Player.rotation = Quaternion.Euler(0, mouseX, 0);
}
}
For Target and Player variable I selected the player object.
Do someone has a simple solution I can understand?
You could simply take the direction and rotate it along with the object that component is attached to using Quaternion * Vector3 operator
var rotatedDirection = transform.rotation * direction;
Or if you rather need the orientation of the other script attached to a different object then do e.g.
// link your camera or whatever shall be used for the orientation via the Inspector
[SerializeField] private Transform directionProvider;
and then
var rotatedDirection = directionProvider.rotation * direction;
Since you're getting the rotation directly from a Transform, you could use Transform.TransformDirection:
Vector3 rotatedDirection = transform.TransformDirection(direction);

My player is not moving Using transform.position in Unity 2d

I am making a 2D game in Unity. So I used trasform.position += movePos type code to move my player when specific key pressed. I also made some animations. Player is not moving still animation is performing. Everything was working fine before I made the jump animation. But now it isn't working. Can someone suggest me what to do. I hadn't made a repository of code in github so I can't share it.
Here you can watch video what is happening:- https://1drv.ms/v/s!AnUoIDNJEoVSmQylzexBqmA1i8Ur?e=4FhJ5h
and here is my player controls code which is responsible for controls:-
using System.Collections;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
#region variables
// Private variables
private float speed = 15f;
[SerializeField]
private bool isOnGround;
private Quaternion leftMoveRotate = new Quaternion(0f, 180f, 0f, 1f);
private Quaternion rightMoveRotate = new Quaternion(0f, 0f, 0f, 1f);
// Public Variables
public Animator playerAnimator;
#endregion
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("ground"))
{
isOnGround = true;
}
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
if (horizontalInput > 0)
{
DInput();
}
if (horizontalInput < 0)
{
AInput();
}
playerAnimator.SetFloat("isRunning", Mathf.Abs(horizontalInput));
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.LeftShift))
{
Jump();
}
}
private void Jump()
{
if (isOnGround)
{
transform.position += new Vector3(0f, 4f, 0f); // Jump code
isOnGround = false;
}
}
private void DInput()
{
transform.rotation = rightMoveRotate;
transform.position += new Vector3(0.5f, 0f, 0f) * speed * Time.fixedDeltaTime;
}
private void AInput()
{
transform.rotation = leftMoveRotate;
transform.position -= new Vector3(0.5f, 0f, 0f) * speed * Time.fixedDeltaTime;
}
}
I also have a code of camera following the player and here is that:-
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform player;
public float offSetX = 5f;
public float offSetY = 2.5f;
private void FixedUpdate() {
Vector3 tempPos = transform.position;
tempPos.x = player.position.x;
tempPos.x += offSetX;
tempPos.y = player.position.y;
tempPos.y += offSetY;
transform.position = tempPos;
}
}
and if I remove jump animation from Animator all control works fine. Here is video you can check:-
https://1drv.ms/v/s!AnUoIDNJEoVSmQ2k_o7Fbs0J5_8d?e=tJlayZ
One thing you might have messed up and is not showing in script, is you recorded transform position change in your animation and animation is messing with position.

Categories

Resources