Search Unity

Unity 2D 3rd Person shooter with attached camera

Discussion in '2D' started by Joker86, Apr 23, 2015.

  1. Joker86

    Joker86

    Joined:
    May 8, 2014
    Posts:
    1
    Hi there!

    I am not only completely new to Unity, but rather completely new to scripting at all!

    By now all I have is just a gameobject which I have assigned a sprite to, and that's my player. (The game object being called "Player").

    Now I want to move on the world with WASD, an I want to turn around by moving the mouse left and right, with the camera always being behind my character.

    I am really proud of myself having figured out how to move my character around, and even looking around works with some snippet of code I have copy-pasted from somewhere else. But now my problem shows up:

    Of course I used the "orinary" movement script which you can find when looking for character movement in Unity 2D, which bases on absolute directions.

    if (Input.GetKey (KeyCode.D)) {
    transform.position += (Vector3.right * speed);
    }

    Now obviously this doesn't work, since I need to have the directions always relative to my camera, which is attached to the player object. How can I achieve a simple way to get the controls I want? I would be very grateful for a combination of both movement and looking around, because what I got there most likely is not really usable:

    public float speed;
    void Start () {

    }


    void Update () {


    if (Input.GetKey (KeyCode.D)) {
    transform.position += (Vector3.right * speed);
    }
    if (Input.GetKey (KeyCode.A)) {
    transform.position += (Vector3.left * speed);
    }
    if (Input.GetKey (KeyCode.W)) {
    transform.position += (Vector3.up * speed);
    }
    if (Input.GetKey (KeyCode.S)) {
    transform.position += (Vector3.down * speed);
    }

    Vector3 mousePos = new Vector3(Input.mousePosition.x*100, Input.mousePosition.z, 1);
    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);

    }
    }

    As you can see, the turning around script more or less is just messed around with, and I found out it somewhat works when adding that *100 multiplier, but I guess that's a really bad fix :-/