using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RocketController : MonoBehaviour
{
public float rotationAngle = 45f;
public float thrustSpeed = 5f;
public Rigidbody2D rb;
public bool turnRight = true;
[SerializeField] bool isMoving = false;
[SerializeField] bool isInPortal = false;
[SerializeField] Quaternion initialRotation;
public GameObject gameOverPanel;
private bool inRightWallTrigger = false;
private bool inLeftWallTrigger = false;
private float fixedXPosition;
private bool isColliding = false;
private float collisionCooldown = 0.5f;
private float lastCollisionTime = -1f;
private bool isGameOver = false; // New game over flag
void Start()
{
initialRotation = transform.rotation;
rb = GetComponent<Rigidbody2D>();
rb.isKinematic = true;
}
void Update()
{
if (isGameOver) return; // Prevent further inputs after game over
if (!isInPortal && Input.GetMouseButtonDown(0))
{
if (!isMoving)
{
isMoving = true;
rb.isKinematic = false;
}
RotateRocket();
inRightWallTrigger = false;
inLeftWallTrigger = false;
isColliding = false;
}
if (isColliding && Time.time - lastCollisionTime > collisionCooldown)
{
isColliding = false;
}
}
void RotateRocket()
{
if (turnRight)
{
transform.rotation = initialRotation * Quaternion.Euler(0, 0, -rotationAngle);
}
else
{
transform.rotation = initialRotation * Quaternion.Euler(0, 0, rotationAngle);
}
turnRight = !turnRight;
}
void FixedUpdate()
{
if (isGameOver) return; // Prevent movement after game over
if (isMoving && !isInPortal && !isColliding)
{
if (inRightWallTrigger || inLeftWallTrigger)
{
rb.velocity = new Vector2(0, thrustSpeed);
transform.position = new Vector2(fixedXPosition, transform.position.y);
}
else
{
rb.velocity = transform.up * thrustSpeed;
}
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (!isColliding && other.gameObject.tag == "Wall")
{
Vector3 currentRotation = transform.eulerAngles;
currentRotation.z = 0;
transform.eulerAngles = currentRotation;
isColliding = true;
lastCollisionTime = Time.time;
}
}
public void DisableMovement()
{
isMoving = false;
isInPortal = true;
rb.velocity = Vector2.zero;
rb.angularVelocity = 0f;
rb.isKinematic = true;
isGameOver = true; // Set game over flag
}
}
This is the movement script of the rocket game I made in Unity 2D. However, in this script, if our rocket separates immediately after touching the wall, instead of separating at a 45-degree angle, it continues to move vertically, which is the way we don’t want it to. What we want is for it to continue to move at a 45-degree angle after separating after moving vertically on the wall. Here, I tried to make a zig-zag mechanic to the right and left at 45-degree angles, the basic mechanic works in this code as long as we don’t touch the wall. I’m waiting for your help.