- Home /
Player Looking in Opposite Direction
Basically, if I move my reticle to the top of the screen, the player looks down and vice versa. This also applies horizontally. I am making a top down shooter. Take a look at what I mean:
And here is my code. Very simple.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
public float speed;
public Texture2D reticle;
public float reticleSensitivity;
private CharacterController player;
private Vector3 moveDir;
private Transform myTransform;
private Camera mainCam;
private Vector3 lookDir;
private float camDif;
private Vector2 reticlePos;
void Awake()
{
mainCam = Camera.main;
myTransform = transform;
camDif = mainCam.transform.position.y - myTransform.transform.position.y;
player = GetComponent<CharacterController>();
}
void Update()
{
movement();
}
void movement()
{
reticlePos += new Vector2(Input.GetAxisRaw("360_RightStickHorizontal") * reticleSensitivity * Time.deltaTime, Input.GetAxisRaw("360_RightStickVertical") * reticleSensitivity * Time.deltaTime);
reticlePos = new Vector2(Mathf.Clamp(reticlePos.x, 0, Screen.width), Mathf.Clamp(reticlePos.y, 0, Screen.height));
lookDir = new Vector3(reticlePos.x, reticlePos.y, camDif);
lookDir = mainCam.ScreenToWorldPoint(lookDir);
myTransform.LookAt(lookDir);
moveDir = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
moveDir *= speed;
player.Move(moveDir * Time.deltaTime);
}
void OnGUI()
{
GUI.DrawTexture(new Rect(reticlePos.x - 32, reticlePos.y - 32, 64, 64), reticle);
}
}
Answer by tanoshimi · Dec 01, 2013 at 08:42 AM
"...I am making a top down shooter..." - so shouldn't you be considering x and z coordinates in all your calculations, not x and y?
You're getting mixed up between world, screen and GUI coordinate systems - and you could make this easier on yourself by commenting your code and using better variable names - lookDir changes its context from a screen space position to world space position, for example (and neither one being a "direction").
If you just want the answer given to you on a plate, change the line:
lookDir = new Vector3(reticlePos.x, reticlePos.y, camDif);
to:
lookDir = new Vector3(reticlePos.x, Screen.height - reticlePos.y, camDif);
Wow - you live up to your name, don't you?! I've updated my answer to point out the exact line you need to change, seeing as it seems you completely missed the point of my original reply. You're welcome.
Your answer
Follow this Question
Related Questions
Replacing Gui.DrawTexture or gui textures in C#? 0 Answers
GUI text appears behind drawn texture. 0 Answers
Web player screen corruption 1 Answer
How to draw textures on a GameObject 2 Answers