0
\$\begingroup\$

I have a simple Sprite called Player that has the follow components (Transform, Sprite Renderer, Box Collider 2D, Rigidbody 2D, Player Controller Script). In my Player Controller script I want to update the player's position when a key is pressed.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    Vector2 playerPos;

    // Use this for initialization
    void Start () {

        playerPos = gameObject.transform.position;

    }

    // Update is called once per frame
    void FixedUpdate () {

        if (Input.GetKey("d")) {

            playerPos = new Vector2(playerPos.x + 0.2f, playerPos.y);

        }

    }
}

This script is attached to my gameobject but whenever I press or hold down the 'd' key, nothing happens to the player. Does anyone know how to fix this?

\$\endgroup\$
2
\$\begingroup\$

Vector2 is a C# struct, which is a value type. That means when you assign a Vector2 to a variable, or pass it as an argument/return value, you're copying the value of the Vector2 — not passing around a reference to it.

So when you say

playerPos = gameObject.transform.position;

You are copying the player's current position into playerPos

(You can skip the gameObject at the front, since the MonoBehaviour's transform getter does the same thing)

Everything you do after that is just modifying this copy — you never assign it back to the player transform to actually move the player.

If you want to move the player to the new location, you need to assign the value back to the player's transform:

transform.position = playerPos;

\$\endgroup\$
  • \$\begingroup\$ Thanks! This was the clarification that I was looking for. I'll probably have to look more into structs and the C# language. \$\endgroup\$ – Rowen McDaniel Jun 9 '16 at 0:44
1
\$\begingroup\$

You want something like:

var player = GameObject.Find("Player");

Then

player.transform.position = new Vector2(playerPos.x + 0.2f, playerPos.y)

Check this out: http://answers.unity3d.com/questions/642405/continuous-movement.html

Describes: Moving in one direction continuously and then move the opposite direction continuously when you press a button.

\$\endgroup\$
  • \$\begingroup\$ Thanks for the suggestion, I also wanted to know if it is possible to directly add to the game objects position rather than using it's rigidbody. \$\endgroup\$ – Rowen McDaniel Jun 9 '16 at 0:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.