Johndii1491
Johndii1491

Reputation: 11

How to rotate the player when moving your mouse?

What I mean in my question is that how to make your player rotate automatically when I move my mouse left for example and my whole characters body will rotate and limit its rotation back to a 2D view.

Similar to the game "Rochard" if you guys know it. But I'm having trouble how to figure it out.

This is my Code:

#pragma strict

var spinx : int = 0;
var spiny : int = 0;
var spinz : int = 0;

function Update () {
    transform.Rotate(spinx, spiny, spinz);
}

Upvotes: 1

Views: 33348

Answers (4)

Noblight
Noblight

Reputation: 146

First, I am really sorry to write it in C#. But I hope it can help you. This script is attached to player gameobject.

private Vector3 MousePositionViewport = Vector3.zero;
private Quaternion DesiredRotation = new Quaternion();
private float RotationSpeed = 15;

void Update () {
    MousePositionViewport = Camera.main.ScreenToViewportPoint (Input.mousePosition);
    if (MousePositionViewport.x >= 0.6f) {
        DesiredRotation = Quaternion.Euler (0, 90, 0);
    } else if(MousePositionViewport.x < 0.6f && MousePositionViewport.x > 0.4f){
        DesiredRotation = Quaternion.Euler (0, 270, 0);
    }else {
        DesiredRotation = Quaternion.Euler (0, 180, 0);
    }
    transform.rotation = Quaternion.Lerp (transform.rotation, DesiredRotation, Time.deltaTime*RotationSpeed);
}

Upvotes: 2

Codemaker2015
Codemaker2015

Reputation: 1

The following script should rotate your object according to mouse position,

 using UnityEngine;
 using System.Collections;

 public class RotateClass : MonoBehaviour {
     public float horizontalSpeed = 2.0F;
     public float verticalSpeed = 2.0F;
     void Update() {
         float h = horizontalSpeed * Input.GetAxis("Mouse X");
         float v = verticalSpeed * Input.GetAxis("Mouse Y");
         transform.Rotate(v, h, 0);
     }
 }

Upvotes: 7

Jordi Knol
Jordi Knol

Reputation: 46

You could import the standard player controls package from unity itself and edit the first person controller to your likings. This is what I tend to do when I want a control in my game that can do what you desire.

Upvotes: 1

Milad Qasemi
Milad Qasemi

Reputation: 3049

this script should rotate your object acccording to mouse position

using UnityEngine;
using System.Collections;

     public class MouseLook : MonoBehaviour {

         void Update () {
            Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.z, 10);
            Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
            lookPos = lookPos - transform.position;
            float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

         }
     }

Upvotes: 1

Related Questions