A few errors are popping up in unity when I tried to compose a simple movement script to move the player right and left. Can someone identify the problem and/or present me with an open solution?
Here is my code:
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public int speed = 5;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(gameObject.tag == "Player") {
if(Input.GetKeyDown(KeyCode.A)) {
transform.Translate(Vector3(-1, 0, 0) * Time.deltaTime * speed);
}
}
if(gameObject.tag == "Player") {
if(Input.GetKeyDown(KeyCode.D)) {
transform.Translate(Vector3( 1, 0, 0) * Time.deltaTime * speed);
}
}
}
}
Thanks in advance!
1 Answer
1
When creating a new Vector3, you need the ‘new’ keyword in C# (not necessary in Javascript). Also you use GetKeyDown(). This will only fire for a single frame, so it only move once for each key press. If you want continuous movement, use GetKey() instead. And as @Loius indicated, the tag comparison is not necessary.
using UnityEngine;
using System.Collections;
public class Bug16 : MonoBehaviour {
public int speed = 5;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//if(gameObject.tag == "Player") {
if(Input.GetKeyDown(KeyCode.A)) {
transform.Translate(new Vector3(-1, 0, 0) * Time.deltaTime * speed);
}
//}
// if(gameObject.tag == "Player") {
if(Input.GetKeyDown(KeyCode.D)) {
transform.Translate(new Vector3( 1, 0, 0) * Time.deltaTime * speed);
}
//}
}
}
what errors? there's no need to check this object's tag - just only put this script on the player object
– LoiusAnother note about your usage of the GetKeyDown. This will only return true on the frame that the key was pressed. It will be false after that until it is pressed again. If you want to check if it is still down and as long as it is down (which I think you want for this case) then you need to use GetKey instead.
– Hotshot10101