- Home /
Top Down shooter mouse controls
Hello guys well I am creating a top down 2d shooter, and i have ran in to a problem with my controls. I want to make my player look at the mouse direction in order to be able to aim, but for some reason it seems to be always off from where the mouse is pointing at only in two certain positions does the mouse and player line up. I have a feeling that unity is getting my mouse coordinates wrong when i transfer it to real world coordinates but I am not sure. please help thank you.
using UnityEngine;
using System.Collections;
public class playermovementscript : MonoBehaviour {
public float movementspeed = 5f;
public float bulletspeed = 10f;
public GameObject bullet;
public GameObject shooter;
public Vector3 target;
public Camera camera;
// Use this for initialization
void Start () {
Camera camera;
}
// Update is called once per frame
void Update () {
movement ();
if (Input.GetKeyDown (KeyCode.F)) {
shoot();
}
}
void movement(){
gameObject.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal")*movementspeed,0,Input.GetAxisRaw("Vertical")*movementspeed);
target = camera.ViewportToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,camera.nearClipPlane));
Debug.Log (target);
transform.LookAt (target,Vector3.up);
}
Answer by 13yearoldceo · Oct 10, 2015 at 01:15 PM
Replace" Viewporttoworldpoint" with "screentoworldpoint"
Answer by Chris-Paul · Oct 09, 2015 at 01:28 PM
Here is the code for your "movement" method: (you needed to cast a ray to that object, to know it's actually there)
Rigidbody rigidbody = GetComponent<Rigidbody>();
// Velocity Asigning.
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
rigidbody.velocity = new Vector3(h, 0, v) * movementspeed;
// Getting the mouse position in screen space
// and make a ray from it.
Vector2 mousePosition = Input.mousePosition;
Ray ray = camera.ScreenPointToRay(new Vector3(mousePosition.x, mousePosition.y));
// Actually cast the ray and see if any object was hit.
RaycastHit hitInfo;
if(Physics.Raycast(ray.origin, ray.direction, out hitInfo)) {
// If we hit something with our ray, then that means we have a target;
target = hitInfo.collider.transform.position;
}
// Look at the target;
transform.LookAt(target);
Thank you, but i am trying to avoid using rays for now, but even if i do what if my ray does not anything.
Don't worry I've saw where i went wrong i accidentally used "viewporttoworldpoint" ins$$anonymous$$d of "screentoworldpoint" thank you for the help anyways.
Your answer
Follow this Question
Related Questions
Move Object - Mouse Input Y Axis from Camera 0 Answers
Wrong world point mouse position 1 Answer
Rotate sprite to face direction of movement 1 Answer
Convert Mouse Position to move a cube on 1-axis. 1 Answer
ScreenToWorldPoint error 3 Answers