- Home /
2D multiple direction movement with arrows problem
Hello,
I am creating a 2D horizontal shmup and I can't find what's the problem with movement.
Movement without firing works fine.
Movement with firing (spacebar) with keys WASD works fine.
Movement with firing (spacebar) with arrow keys when moving x axis positive (right) + y axis positive (up) works fine. Same with both axes negative.
Movement with firing (spacebar) with arrow keys when axes are opposite (I.E. x negative, y positive) doesn't work. The character moves in single direction.
Here is the code (problem is probably within Update() function):
using UnityEngine;
using System.Collections;
public class PlaneParameters : MonoBehaviour {
public float fireRate = 0;
public float Speed = 2;
public float movementSpeed = 2;
public Transform bulletPrefab;
private float timeToFire = 0;
private Transform firePoint;
void Awake (){
firePoint = transform.FindChild("FirePoint");
if (firePoint == null){
Debug.LogError ("Can't find Plane child FirePoint");
}
}
void Start (){
}
// Update is called once per frame
void Update () {
// movement with camera
transform.Translate(Vector3.right * Speed * Time.deltaTime);
//player input movement
if (Input.GetButton ("Horizontal")){
transform.Translate(new Vector3 (Input.GetAxis("Horizontal") * movementSpeed * Time.deltaTime,0f,0f));;
}
if (Input.GetButton ("Vertical")){
transform.Translate(new Vector3 (0f,Input.GetAxis("Vertical") * movementSpeed * Time.deltaTime,0f));
}
//restrictions within screen
var pos = Camera.main.WorldToViewportPoint(transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
transform.position = Camera.main.ViewportToWorldPoint(pos);
//firing
if (Input.GetKey (KeyCode.Space) && Time.time > timeToFire){
timeToFire = Time.time + 1/fireRate;
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
}
void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.tag == "Enemy")
{
Application.LoadLevel("restartScreen");
}
}
}
Any ideas what's wrong?
Thanks in advance.
Answer by Gabriel Saldanha · Feb 20, 2015 at 06:17 PM
I think I did not understand the problem.. When you press, for example, Right (X-positive) and Down (Y-negative), the movement is happening in only one of these directions?
I guess you could you try removing the "if(GetButton("Vertical/Horizontal"))" before the
transform.Translate(new Vector3 (0f,Input.GetAxis("Vertical") movementSpeed Time.deltaTime,0f));
Doesn't work. Well yeah, when you press right + down the movement works only to the direction you pressed first.
Your answer
![](https://koobas.hobune.stream/wayback/20220613183834im_/https://answers.unity.com/themes/thub/images/avi.jpg)