Unity3D character facing in the direction it’s moving - c#

I am making a game, it contains planetary gravity, how would I be able to make the player look in the direction it’s moving, would be helpful if I could insert it to my movement code
using UnityEngine;
public class PlayerMovementScript : MonoBehaviour {
public float moveSpeed;
private Vector3 moveDirection;
void Update()
{
moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
}
void FixedUpdate()
{
GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + transform.TransformDirection(moveDirection) * moveSpeed * Time.deltaTime);
}
}

Assuming that this script is attached to the object you want to have point at its movement direction, try this.
void Update()
{
moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
Vector3 lookDirection = moveDirection + gameObject.Transform.Position;
gameObject.Transform.LookAt(lookDirection);
}
Because your moveDirection is normalized, you have to add it to your current position in order to get the moveDirection in the object's local space. Then you can LookAt() it to point towards it.

You can look in the direction you're moving by using the rigidbody's velocity.
transform.rotation = Quaternion.LookRotation(rb.velocity);
If you want a smoothed transition:
Quaternion desiredRotation = Quaternion.LookRotation(rb.velocity);
transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, Time.deltaTime);

Related

How do I Detect if the Mouse is Moving on Screen in Unity?

I am making a 360 camera movement for my game called PROTOTYPE. I need a function or something to detect if the mouse is moving and in which direction on the x axis it is, to set an offset for the Camera Smoothing script, but I don't know any. Could somebody plz help me? Here is the Camera Smoothing script if u need it:
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
void FixedUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt(target);
}
}
I suppose you want to move your camera with your mouse, 360° around your character and also that script is attached to your player.
In order to do that, your FixedUpdate should look like this:
void FixedUpdate()
{
float horizontalAxis = Input.GetAxis("Mouse X"); // Getting the current mouse axis (left-right)
float verticalAxis = Input.GetAxis("Mouse Y"); // Getting the current mouse axis (up-down)
transform.RotateAround(player.transform.position, -Vector3.up, horizontalAxis * smoothSpeed);
transform.RotateAround(Vector3.zero, transform.right, verticalAxis * smoothSpeed);
}

Unity: player acts weirdly when I release movement input

Good day everyone!
I was trying to make my player face the direction he's walking towards, but then weird things started happening. Whenever I now let go of my input keys, the player slowly gets sucked to his local z-axis. Sometimes he does this while standing up, sometimes he does this flipped.
Any help would be highly appreciated!
Thanks in advance!
I'll provide you with my script:
public class JackMovement3D : MonoBehaviour {
public float speed = 6.0F;
public float VerticalSpeed = 10f;
public float HorizontalSpeed = 60f;
public float rotationSpeed = 5f;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private Animator animator;
private void Start()
{
animator = GetComponent<Animator>();
}
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
// is the controller on the ground?
if (controller.isGrounded)
{
float horizontal = Input.GetAxis("Horizontal") * HorizontalSpeed;
float vertical = Input.GetAxis("Vertical") * VerticalSpeed;
//Feed moveDirection with input.
moveDirection = new Vector3(horizontal, 0, vertical);
moveDirection = transform.TransformDirection(moveDirection);
//Multiply it by speed.
moveDirection *= speed;
}
//Applying gravity to the controller
moveDirection.y -= gravity * Time.deltaTime;
animator.SetFloat("Blend", controller.velocity.magnitude);
//Look at walking direction
Quaternion newRotation = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, rotationSpeed);
// CharacterController.Move to move the player in target direction
controller.Move(moveDirection * Time.deltaTime);
}
private void LateUpdate()
{
transform.localEulerAngles = new Vector3(0, transform.localEulerAngles.y, transform.localEulerAngles.z);
}
}
Not sure if this is the issue you describe but it might be related to
Quaternion.LookRotation(moveDirection);
since if there is no Input the moveDirection is a Vector3(0,0,0) and Quaternion.LookRotation
Returns identity if forward or upwards magnitude is zero.
so you could probably avoid that resetting the rotation to idendity by adding a check like
// if movement is 0 do nothing else
if(Mathf.Approximately(moveDirection.sqrMagnitude, 0)) return;
this should be before adding the gravity.
Actually not sure again but I guess the gravity should be added after
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
// is the controller on the ground?
if (controller.isGrounded)
{
float horizontal = Input.GetAxis("Horizontal") * HorizontalSpeed;
float vertical = Input.GetAxis("Vertical") * VerticalSpeed;
//Feed moveDirection with input.
moveDirection = new Vector3(horizontal, 0, vertical);
moveDirection = transform.TransformDirection(moveDirection);
//Multiply it by speed.
moveDirection *= speed;
}
animator.SetFloat("Blend", controller.velocity.magnitude);
// if movement is 0 do nothing else
if(Mathf.Approximately(moveDirection.sqrMagnitude, 0))
{
return;
}
moveDirection.y -= gravity * Time.deltaTime;
//Look at walking direction
var newRotation = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, rotationSpeed);
// CharacterController.Move to move the player in target direction
controller.Move(moveDirection * Time.deltaTime);
}

unity 3d rotate object (space.self) toward player

i need your help please.
i want an object to rotate in Y axis (space.self) toward the player position.
i have already tried this code, it works but i think there is a bug in it because the object keep changing position slowly.
public Transform _Playertrs;
public float RotationSpeed = 10f;
private Quaternion _LookRotation;
private Vector3 _direction;
private bool Patroling = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
_direction = (_Playertrs.position - transform.position).normalized;
_LookRotation = Quaternion.LookRotation(_direction);
transform.rotation = Quaternion.Slerp(transform.rotation, _LookRotation, Time.deltaTime * RotationSpeed);
}
thank you guys for your answers, the rotation is working perfectly now, but the problem is the object keep moving from its position even that i don't have any movement code, watch the video to understand pls
https://www.youtube.com/watch?v=Gys5xYQ5psw&feature=youtu.be
If you want it to be instantaneous, replace
transform.rotation = Quaternion.Slerp(transform.rotation, _LookRotation, Time.deltaTime * RotationSpeed);
by
transform.rotation = _LookRotation;
The Slerp function gives an intermediate point between the to rotation to make a smooth effect.
Here, this is taken from the Unity Quaternion.LookRotation() official documentation, you can just simply apply the Quaternion that you have _LookRotation and apply it to your desired transform.rotation as such transform.rotation = _LookRotation;
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Transform target;
void Update() {
Vector3 relativePos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
transform.rotation = rotation;
}
}

Drag GameObject With Mouse

I am having some issues with creating a script that once the player clicks upon a gameObject that gameObject will follow the mouse. The object will be dropped once the mouse is clicked again.
Here is the script:
public float distance = 10;
public void OnMouseDrag()
{
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = objPosition;
}
This works fine, but the issue is if the player (the main cam) has any sort of movement script upon it such as this Character controller script on it or its parent, then the gameObject that is picked up will move around as if it is trying to get away from the mouse.
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
if(Input.GetKey(KeyCode.LeftShift))
{
speed = 15.0f;
}else
{
speed = 6.0f;
}
if(controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
if(Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
float rotateRight = Input.GetAxis("Mouse X");
transform.Rotate(0, rotateRight, 0);
}
If the above script is disabled, then the GameObject does not freak out and it works fine.
I know that the input being made in the character controller is effecting the top script in some way, the mouse moving so the gameObject transforms in that direction while trying to keep to a certain point on the mouse.
But how to I make so it won't effect it.
I bet the mouse dragging is happening before your movement.
Try putting your dragging logic in LateUpdate() so it can accommidate for the new position

How to automatically rotate turrets towards enemy direction continously?

I have a turret placed as a game-object ,i have set the target as enemy in inspector,but somehow the turrets just point towards my enemy but are not continuously rotating on z axis.what is the problem,any help thanx...!!
Here is my code
using UnityEngine;
using System.Collections;
public class TurretScript: MonoBehaviour
{
public Transform target;
void Update()
{
Vector3 tarPos = new Vector3(target.position.x, target.position.y, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(tarPos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
Easiest way to achieve this? Cheat! Something like this:
public class TurretScript: MonoBehaviour
{
//values that will be set in the Inspector
public Transform Target;
public float RotationSpeed;
void Update()
{
var direction = Target.transform.position - transform.position;
// Set Y the same to make the rotations turret-like:
direction.y = transform.position.y;
var rot = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rot,
RotationSpeed * Time.deltaTime);
}
}
You can also use Transform.LookAt() from the Documentation
I find this to be the simplest approach without the headache of computing rotations.

Categories