My code:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
public Rigidbody2D player;
public float jumpForce;
public float maxSpeed;
void Start () {
player.velocity = new Vector2 (0, 0);
}
void FixedUpdate() {
if (player != null) {
if (player.velocity.y > maxSpeed) {
player.velocity = new Vector2 (player.velocity.x, maxSpeed);
}
if (player.velocity.x > maxSpeed) {
player.velocity = new Vector2 (maxSpeed, player.transform.position.y);
}
}
}
void Update () {
if (player != null) {
if (Input.GetMouseButtonDown(0)) {
if (Input.mousePosition.x > Screen.width / 2) {
//player.velocity = new Vector2 (player.velocity.x, player.velocity.y + jumpForce);
player.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
} else if (Input.mousePosition.x < Screen.width / 2) {
//player.velocity = new Vector2 (player.velocity.x + jumpForce, player.velocity.y);
player.GetComponent<Rigidbody2D>().AddForce(new Vector2(jumpForce, 0), ForceMode2D.Impulse);
}
}
if (player.transform.position.x < -12.5 || player.transform.position.y < -21) {
SceneManager.LoadScene (0);
}
if (player.transform.position.x > 10.25) {
player.transform.position = new Vector2 (10.25f, player.transform.position.y);
player.velocity = new Vector2 (player.velocity.x * -0.1f, player.velocity.y);
}
}
}
}
Is meant to make the player jump to the right if you click on the left half of the screen, and jump up if you click on the right half. However, sometimes when I click the left half, the player will go up! (Usually when you get further into the level for some reason). P.S. I have gravity activated on the X and Y axes…
EDIT
I just attempted to use AddForce() on the player instead of changing the velocity. The same behaviour still occurs.
EDIT #2
I commented out the FixedUpdate stuff and it worked, but now I need to make it so it can’t go super duper fast