Untitled
unknown
plain_text
a year ago
2.0 kB
7
Indexable
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
private Rigidbody2D rb;
private bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
// Player movement
float horizontalInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
// Jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
}
}
}
using UnityEngine;
public class ObstacleSpawner : MonoBehaviour
{
public GameObject obstaclePrefab;
public float spawnInterval = 2f;
private float timer;
void Update()
{
timer += Time.deltaTime;
if (timer >= spawnInterval)
{
SpawnObstacle();
timer = 0f;
}
}
void SpawnObstacle()
{
// Instantiate a new obstacle at a random position
float spawnX = transform.position.x;
float spawnY = Random.Range(-3f, 3f);
Instantiate(obstaclePrefab, new Vector2(spawnX, spawnY), Quaternion.identity);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Obstacle"))
{
// Game Over logic here
Debug.Log("Game Over");
// Optionally: Application.Quit(); // To quit the application
}
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
Editor is loading...
Leave a Comment