- Home /
Spyro/Mario 64-like controls and camera
Hey,
I'm using the MouseOrbitImproved script and I'd like to make it influence the player's controls.
For exemple, if I press "left" after I have rotated my camera by 20 degrees, the character would rotate toward the left of the camera's POV and advance in that direction. Exactly like in Mario 64, Spyro or Rayman 2: video
I tried different things with controls, but since I didn't succeed in my experiments, I simplified it to the maximum:
void Update () {
if (Input.GetKey(KeyCode.LeftArrow)) {
Move(Vector3.left);
}
if (Input.GetKey(KeyCode.RightArrow)) {
Move(Vector3.right);
}
if (Input.GetKey(KeyCode.UpArrow)) {
Move(Vector3.forward);
}
if (Input.GetKey(KeyCode.DownArrow)) {
Move(Vector3.back);
}
}
void Move(Vector3 direction)
{
transform.Translate(direction * Time.deltaTime * movementSpeed, Space.World);
}
I tried to replace "Space.World" by "camera.transform" but it makes it move upward/downward and I don't see how I could set player's rotation from this.
Answer by Kusanageek · Mar 04, 2013 at 06:12 PM
Got it working, although it probably needs improvements... Here's the sample code in case people have the same question:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float movementSpeed = 10;
public GameObject DirectionObject;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.A)) {
Move(Vector3.left);
}
if (Input.GetKey(KeyCode.D)) {
Move(Vector3.right);
}
if (Input.GetKey(KeyCode.W)) {
Move(Vector3.forward);
}
if (Input.GetKey(KeyCode.S)) {
Move(Vector3.back);
}
}
void Move(Vector3 direction)
{
var newDirection = Quaternion.LookRotation(Camera.main.transform.position - transform.position).eulerAngles;
newDirection.x = 0;
newDirection.z = 0;
DirectionObject.transform.rotation = Quaternion.Euler(newDirection);
transform.Translate(-direction * Time.deltaTime * movementSpeed, DirectionObject.transform);
Quaternion newRotation = Quaternion.LookRotation(-direction);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation * DirectionObject.transform.rotation, Time.deltaTime * 8);
}
}
Works like a charm with MouseOrbitImproved!
Your answer
Follow this Question
Related Questions
How can I mimic this game's camera in Unity? 1 Answer
Changing the camera from first person to third person. 1 Answer
Need help with scripting for product visualisation! 1 Answer
WASD Movement with Mouse position dictating which way the character is facing 1 Answer
Character controller and MouseOrbit Camera(don't work togheter) 2 Answers