How do i make my character move in the direction of the camera (Unity) - unity3d

In Unity I want to make it so that when I hold w, instead of going in a single direction I want it to go forward in the direction of my camera how do I do that? (Sorry I'm new to unity)
EDIT: The movement script is:
using UnityEngine;
using System.Collections;
public class Player_Movement : MonoBehaviour {
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 (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);
}
}

As indicated by #lockstock, the direction the camera is facing can be retrieved from its transform. Here is an example below if you want to know how to use it.
public class Player_Movement : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
// Drag & Drop the camera in this field, in the inspector
public Transform cameraTransform ;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = cameraTransform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
This scripts works without any error. I've tested it in Unity myself.

The forward direction of the camera is obtained by using Camera.main.transform.forward

turn your player so the blue axis is facing the same direction as the blue axis on the camera. then drag and drop the camera onto the player. now when you move the player, the camera will follow, and stay behind the player

Related

Unity 3D Movement Problem when moving backward, if statement not the issue

This script in Unity allows me to move my player forward, left and right but not backwards. This script also allows me to turn the player and move in the direction of the camera.
However, When pressing the back arrow the player spins and moves randomly.
I tried removing the "if" statement, didn't help.
Totally stuck, please help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovment : MonoBehaviour
{
public Transform cam;
public float speed = 6f;
public CharacterController controller;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void FixedUpdate()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0f, verticalInput).normalized;
if (movementDirection.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(movementDirection.x, movementDirection.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f,angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}

Why is my character falling/leaning over on mouse click in unity?

My character using CharacterController seems to be falling over! Is it the rotation that's the issue? I've been hitting my head against the wall for a few days trying to get this solved. any thoughts?
an small vid of what's happening: https://imgur.com/a/AyPvLtm
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
public class Player : MonoBehaviour
{
[SerializeField] private float playerSpeed = 10f;
[SerializeField] private float rotationSpeed = 8f;
public float SpeedChangeRate = 10.0f;
private Camera mainCamera;
private Vector3 targetPosition;
private CharacterController characterController;
private Coroutine coroutine;
private int groundLayer;
private void Awake() {
mainCamera = Camera.main;
characterController = GetComponent<CharacterController>();
groundLayer = LayerMask.NameToLayer("Ground");
}
void Update()
{
if (Mouse.current.leftButton.isPressed) Move();
}
private void Move() {
Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
Physics.Raycast(ray: ray, hitInfo: out RaycastHit hit);
if (hit.collider && hit.collider.gameObject.layer.CompareTo(groundLayer) == 0) {
if (coroutine != null) StopCoroutine(coroutine);
coroutine = StartCoroutine(PlayerMoveTowards(hit.point));
targetPosition = hit.point;
}
}
private IEnumerator PlayerMoveTowards(Vector3 target) {
while (Vector3.Distance(transform.position, target) > 0.1f) {
Vector3 destination = Vector3.MoveTowards(transform.position, target, playerSpeed * Time.deltaTime);
Vector3 direction = target - transform.position;
Vector3 movement = direction.normalized * playerSpeed * Time.deltaTime;
characterController.Move(movement);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction.normalized), rotationSpeed * Time.deltaTime);
yield return null;
}
}
}
The reason is that at close distances, the difference between the main player's Target and Pivot point becomes very small and the height will be effective in determining the direction. Just set the direction Y to 0 to solve the problem.
Vector3 direction = target - transform.position;
direction.y = 0;
Figured this out.
It was my capsule collider. I had it set to the X-Axis, causing the collider to be rotated 90 degrees.
So my character would move and then flip to the side. Updating the collider direct to be on the Y-Axis fixed the problem.

Unity2D - Enemy shoot at player in a cone shaped pattern

I am trying to set up an enemy that will shoot at the player in a cone shape/shotgun shape. If I set the projectile script to transform.position += transform.right * m_Speed * Time.deltaTime; then the cone shape works as intended, just only to the right and not in the direction of the player. With the current setup (below), the projectile will shoot at the player, but all the bullet prefabs will be on top of each other and all going in the same direction, not in a cone shape.
How can I adjust this so the enemy will shoot at the player but retain the cone shape?
Enemy Script
aimAngle = 60f;
for (int i = 0; i < spreadShot; i++)
{
var shotRotation = gameObject.transform.rotation;
shotRotation *= Quaternion.Euler(0, 0, aimAngle);
GameObject clone = Instantiate(projectile, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y), shotRotation);
aimAngle = aimAngle - 30f;
Vector3 direction = (Vector3)((player.transform.position - transform.position));
direction.Normalize();
clone.GetComponent<Projectile>().Setup(direction);
}
Projectile.cs
[SerializeField] float m_Speed;
Vector3 shootDir;
public void Setup(Vector3 shootDir)
{
this.shootDir = shootDir;
}
private void Update()
{
transform.position += shootDir * m_Speed * Time.deltaTime;
}
Not perfect yet but here is a working solution if anyone else has the same question.
Enemy Script
[SerializeField] public float attackSpread;
[SerializeField] private float startShotTime;
[SerializeField] private float delayShotTime;
[HideInInspector] public int spreadShot;
public void Attack() {
Vector2 targetPosition = target.transform.position - aimIndicator.transform.position;
Vector2 dirTowardsTarget = (targetPosition - (Vector2)transform.position);
transform.right = targetPosition.normalized;
Quaternion newRot;
for (int i = 0; i < spreadShot; i++)
{
float addedOffset = (i - (spreadShot / 2)) * attackSpread;
newRot = Quaternion.Euler(transform.localEulerAngles.x,
transform.localEulerAngles.y,
transform.localEulerAngles.z + addedOffset);
Instantiate(projectile).GetComponent<ButcherProjectile>().SpawnBullet(transform.position, newRot);
}
}
Projectile Script
[SerializeField] private float MovementSpeed = 10;
private Vector2 velocity;
public void SpawnBullet(Vector3 position, Quaternion rotation)
{
transform.position = position;
transform.rotation = rotation;
velocity = transform.right.normalized * MovementSpeed;
}
public void Update()
{
Vector2 nextPosition = (Vector2)transform.position + (velocity * Time.deltaTime);
transform.position = nextPosition;
Destroy(gameObject, 2f);
}
At the moment, your code rotates the bullet itself, not the vector of direction towards player. Shot rotation you computed doesn't affect your direction in any way.
To elaborate, if you rotate an object and just move it by transform.position, you changed its position by exactly how you specified, as if you just changed its x, y or z component by hand. Your rotation change to an object would produce desired results if you used transform.Translate(params) as this operation is dependant on object's current rotation and scale.
Apply your rotation to the direction, it should work just fine :)
More reference on how to do it: https://answers.unity.com/questions/46770/rotate-a-vector3-direction.html

CHARACTER ROTATION depending on camera IN UNITY

I'm making a 3rd person controller in unity and i'm stuck: i can't figure out how to make the player follow my freelook cinemachine.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public GameObject Hoverboard_script;
public GameObject cinemachine_Hoverboard;
public Transform main_cam_tf;
void Update()
{
Hoverboard_script.SetActive(false);
cinemachine_Hoverboard.SetActive(false);
PlayerMovement_void();
CamController_void();
}
void PlayerMovement_void()
{
float hor = Input.GetAxisRaw("Horizontal");
float ver = Input.GetAxisRaw("Vertical");
Vector3 playerMovement = new Vector3(hor, 0f, ver).normalized * speed * Time.deltaTime;
transform.Translate(playerMovement, Space.Self);
}
void CamController_void()
{
float MouseY = main_cam_tf.eulerAngles.y;
Debug.Log(MouseY);
Quaternion rotation = Quaternion.Euler(0f, MouseY, 0f);
transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * 4f);
}
}
Right now if i rotate the camera, the player enters a non-stop loop where it rotate constantly. How can i solve? Thanks, cheers
If you want to rotate the player as the rotation value of Y of Camera then remove all the lines of codes in which they rotate your object. Instead use one of these:
1.
transform.rotation = Quaternion.AngleAxis(Camera.Main.transform.eulerAngles.y, Vector3.up);
transform.rotation = Quaternion.EulerAngles(transform.eulerAngles.x, Camera.Main.transform.eulerAngles.y, transform.eulerAngles.z);

How to jump smoothly in Unity3D

I add a CharacterController to Player.But when I test the jump function,I find that the Player will move upwards immediately.
if (Player.isGrounded)
{
if (jump)
{
Move.y = JumpSpeed;
jump = false;
Player.Move (Move * Time.deltaTime);
}
}
Move += Physics.gravity * Time.deltaTime * 4f;
Player.Move (Move * Time.fixedDeltaTime);`
You are calling Player.Move() twice in one frame. This might be an issue.
You are adding gravity to Move vector, which means it will always go upward when you call this code.
naming a variable like Move is not a good convention. It creates confusion while reading because there is already a method of same name. change it to moveDirection.
Here is sample code:
public class ExampleClass : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update() {
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);
}
}
hope this helps.