Currently working on a top down game but can’t get the movement working properly.
I want the object to move towards the mouse when I press W but it simply goes up. Same when I press S: instead of backing away from mouse it just goes down.
code:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float playerSpeed = 12;
// START - Use this for initialization
void Start () {}
// UPDATE is called once per frame
void Update () {
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * Time.deltaTime * playerSpeed, Space.World);
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * Time.deltaTime * playerSpeed, Space.World);
}
}
Well, you don’t say anything about the mouse in your code, why would it?
You probably need to send a ray into the world from the mouse position and then have the object turn toward it with look at, then you can use the keys to go forward or reverse.
I’m using a different script for the rotation with the mouse.
Here’s that code:
using UnityEngine;
using System.Collections;
public class MouseRotate : MonoBehaviour {
public float speed;
public Transform target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
Vector3 MS = Camera.main.ScreenToWorldPoint(mousePos);
MS.y = transform.position.y;
transform.LookAt(MS);
}
}
Ok, if it’s a top down game, you want the object to look at the x and z position of the camera, but the y position of the object because the camera is up in the air. You are using LookAt in that script, so it’s similar. After you call lookat for the object, then you can apply translation locally.
This is what Im currently using to control the player in my TopDown that has the player move towards the mouse, and it operates exactly how you described you wanted.
W moves player towards mouse position, S moves player away from mouse.
using UnityEngine;
using System.Collections;
public class PlayerMobility : MonoBehavior
{
// Player's Speed Variable
public float speed;
void FixedUpdate() {
// This is getting the mouse's current position and rotating the object to face it.
var mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Quaternion rotation = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward);
transform.rotation = rotation;
transform.eulerAngles = new Vector3(0,0, transform.eulerAngles.z);
// Optional
rigidbody2D.angularVelocity = 0;
// Now move the rotated object
var input = Input.GetAxis ("Vertical");
rigidbody2D.AddForce(gameObject.transform.up * speed * input);
}
You will want to adjust the rigidbody’s Angular Drag and the object’s speed variable to get it how you want it to feel.
@BenZed has it right. I’ve got a ton of projects that move based on a body forward just so the camera forward doesn’t make you walk into the air when making an fps lol.