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!
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);
}
//}
}
}