using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerMovement : MonoBehaviour {
public Rigidbody2D rb;
public float speed;
public float speed_x_constraint;
private bool jumping;
// variables for random jump force
public float jumpForceMin;
public float jumpForceMax;
void Start() {
rb = gameObject.GetComponent<Rigidbody2D>();
speed_x_constraint = 5f;
jumping = false;
speed = 0.1f;
// set the minimum and maximum jump force values
jumpForceMin = 1f;
jumpForceMax = 2f;
}
void Update() {
if (Input.GetKey(KeyCode.RightArrow)) {
rb.AddForce(new Vector2(100 * speed, 0f), ForceMode2D.Force);
}
if (Input.GetKey(KeyCode.LeftArrow)) {
rb.AddForce(new Vector2(-100 * speed, 0f), ForceMode2D.Force);
}
if (!jumping && Input.GetKey(KeyCode.UpArrow)) {
// generate a random jump force value between the minimum and maximum values
float jumpForce = Random.Range(jumpForceMin, jumpForceMax);
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
if (rb.velocity.x > speed_x_constraint) {
rb.velocity = new Vector2(speed_x_constraint, rb.velocity.y);
}
if (rb.velocity.x < -speed_x_constraint) {
rb.velocity = new Vector2(-speed_x_constraint, rb.velocity.y);
}
}
void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.tag == "Platform") {
jumping = false;
}
}
void OnTriggerExit2D(Collider2D collision) {
if (collision.gameObject.tag == "Platform") {
jumping = true;
}
}
}
This script adds two new variables jumpForceMin and jumpForceMax which define the minimum and maximum jump force values. When the player jumps by pressing the up arrow key, a random jump force is generated within the defined range and applied to the player. This way, the player can jump different heights randomly.