1
\$\begingroup\$

I've made an empty game object which is the child of the player. It is by default on his right side and following his every move, and I want to make it so that every time a directional key is pressed (WASD) it changes position and stays there. But the way I've made it, it's not working as intended and seemingly goes to random positions every time. Here's the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangePositionAccordingToKey : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            transform.position = new Vector3(-0.58f, 3.09f,0);
        }
    }
}

This is probably a dumb question but I am new to coding so I can't figure it out. Any help is greatly appreciated

\$\endgroup\$
  • 1
    \$\begingroup\$ It doesn't look like the problem comes from this script alone. Can you try placing this script in a brand new, empty project, to see if you can reproduce the problem there? Port over stuff from your old project until the problem re-appears, and that will help you identify which other bits of code or scene setup are relevant to the issue. \$\endgroup\$ – DMGregory May 17 at 13:39
  • \$\begingroup\$ It is easier to use Unity's built-in input system, you can find it under the edit menu > project settings > input. You can then use horizontal +=Input.GetAxis("Horizontal"); to move around \$\endgroup\$ – x13 May 17 at 14:26

Your Answer

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

Browse other questions tagged or ask your own question.