- Home /
Question by
Sansgamer120 · Jan 16, 2021 at 12:08 AM ·
movementmovedirection
how to make player move where you are looking
how would i make my script always move my character where it is looking. here is my script, it is for mobile btw.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class SC_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;
public float distance = 5;
CharacterController characterController;
Vector3 moveDirection = Vector3.zero;
float rotationX = 0;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
// We are grounded, so recalculate move direction based on axes
float movementDirectionY = moveDirection.y;
if ((Input.GetButton("Jump") || SC_MobileControls.instance.GetMobileButtonDown("Jumping")))
{
moveDirection.y = jumpSpeed;
}
else
{
moveDirection.y = movementDirectionY;
}
// Move the controller
characterController.Move(moveDirection * Time.deltaTime);
// Player and Camera rotation
{
#if UNITY_IPHONE || UNITY_ANDROID || UNITY_EDITOR
rotationX += -(SC_MobileControls.instance.GetJoystick("JoystickRight").y) * lookSpeed;
#else
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
#endif
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
#if UNITY_IPHONE || UNITY_ANDROID || UNITY_EDITOR
transform.rotation *= Quaternion.Euler(0, SC_MobileControls.instance.GetJoystick("JoystickRight").x * lookSpeed, 0);
#else
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
#endif
}
}
}
Comment
Answer by CmdrZin · Jan 16, 2021 at 05:45 AM
If you use a Vector3.forward as your direction component, the object will move in the direction it is facing.
Your answer
![](https://koobas.hobune.stream/wayback/20220613023352im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Get device moving direction like Left to Right and Top to Bottom. 0 Answers
Changing walking speed in CharacterController.Move 1 Answer
Player Rotation 1 Answer
CharacterController sprint functionality. 1 Answer
Character movement problem 0 Answers