Question by
Iquit · Jul 15, 2017 at 11:09 PM ·
c#2d game2d-physics2d-gameplay2d platformer
Im making a test game for 2D movement since Im new at the game but when I press spacebar it doesnt do anything but it says its working
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerScript : MonoBehaviour {
private Rigidbody2D rb;
public float speed = 15f;
public Vector2 Up = new Vector2(0, 5000);
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
if (Input.GetKeyDown(KeyCode.Space))
{
rb.MovePosition(Up);
Debug.Log("Spacebar Pressed");
}
float x = Input.GetAxis("Horizontal") * Time.fixedDeltaTime * speed;
Vector2 newPos = rb.position + Vector2.right * x;
rb.MovePosition(newPos);
}
}
Comment
Answer by Bunny83 · Jul 15, 2017 at 11:43 PM
Do not check one time input (anything with Down or Up in the name) inside FixedUpdate. FixedUpdate usually runs at a slower rate. However the input is only true for one frame. Since FixedUpdate doesn't run every frame it can "miss" that event.
Answer by Iquit · Jul 16, 2017 at 12:02 AM
Never Mind I figured it out kind of
private Rigidbody2D rb;
public float speed = 15f;
public Vector2 Up = new Vector2(0, 5000);
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
if (Input.GetKeyDown(KeyCode.Space))
{
rb.position = Up;
Debug.Log("Spacebar Pressed");
}
float x = Input.GetAxis("Horizontal") * Time.fixedDeltaTime * speed;
Vector2 newPos = rb.position + Vector2.right * x;
rb.MovePosition(newPos);
}
}