- Home /
Make character rotate by using the mouse
Hi! I am a beginner at scripting, could someone help in this? I sincerely don't know what to do. I have a script that allow the player to go forward,backward,left and right. BUT i want to also be able to rotate the character by using the mouse. Not rotate it like, 90° degrees down or something. I wanted to make something that would POINT the player to the mouse's direction.
Examples:
Here's my script:
using UnityEngine;
using System.Collections;
public class CharMove : 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);
}
}
Could someone help me?
Answer by Bigiansen · Sep 07, 2016 at 09:48 PM
You could use something like this:
transform.LookAt(Camera.main.ScreenToWorldPoint(Input.mousePosition));
Answer by Lewwwer · Sep 07, 2016 at 08:53 PM
Hello!
First I would try to convert the mouse position to world position using
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
This enables us to use the LookAt function to rotate our object to a specified position. So
transform.LookAt(mousePos);
So the code should look like this:
using UnityEngine;
using System.Collections;
public class CharMovement : MonoBehaviour
{
public float speed;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
//The new code:
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(mousePos);
}
}
Hope I didn't make a typo...
Sorry, It may not work properly, depending on the original direction of your object.
I would try to make the gun to be the child of the player, and see where it is facing using this code. After the results I would adjust the position of the gun.
Your answer
Follow this Question
Related Questions
Disabling character controller after collision 2 Answers
Parenting Player to platforms, not parenting on the second platform? 2 Answers
How do i toggle active a game object?? 2 Answers
How do I make a script that will allow my character to shoot projectiles? 1 Answer
Collison detection not working? 1 Answer