Unity Why wont my FPS pause menu stop the camera rotation? - c#

I am working on the pause menu for my FPS game and so far I am able to get the pause menu panel to show up and interact with it, but it does not stop the camera movement. Can someone tell me what I am doing wrong?
Here is the code:
public class PauseMenuu : MonoBehaviour
{
public static bool GameIsPaused = false;
public GameObject PauseMenu;
private void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (GameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
void Resume()
{
PauseMenu.SetActive(false);
Time.timeScale = 1f;
GameIsPaused = false;
}
void Pause()
{
PauseMenu.SetActive(true);
Time.timeScale = 0f;
GameIsPaused = true;
}
}
here is my camera rotate code if this helps you figure out what is going on with the camera.
public class CameraRotate : MonoBehaviour
{
public float speed;
float time = 14.0f;
public GameObject HeadCamera;
public bool updateOn = true;
void Start()
{
StartCoroutine(updateOff());
}
void Update()
{
Rotation();
}
void Rotation()
{
RotateX += Input.GetAxis("Mouse X") * RotationSpeed;
RotateY += Input.GetAxis("Mouse Y") * RotationSpeed;
RotateY = Mathf.Clamp(RotateY, MinYAxis, MaxYAxis);
Camera.transform.localRotation = Quaternion.Euler(-RotateY, 0f, 0f);
transform.rotation = Quaternion.Euler(0f, RotateX, 0f);
}
}

It could solve it for you, try rotating the camera relative to its own position. So what you would do is add this to the top of your function call:
void Rotation()
{
if(Time.deltaTime == 0){
return;
}
...
Also note that you might need to change a couple of values to get the rotation amount like before.
Hope it helps!

Related

Player now does not jump after adding health in Unity

so first time learning C# for my team studio class. I found this video which I was able to get my player moving and jumping perfectly, https://www.youtube.com/watch?v=3GtQ2yQX2kU&t=569s however after I added a health/can die system to the script, now the player refuses to jump no matter what I do. Since I am a newbie at this, I am just going to post the whole thing here if anyone can point me in the right direction. I've played with the box colliders, added the layers to the platforms like the tutorial said... please, if anyone can help. I know I'm a newbie to this :(
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public HealthBar healthBar; //Communicates with the healthbar script
public float moveSpeed;
public float jumpForce;
public int jumpsAmount;
int jumpsLeft;
public Transform GroundCheck;
public LayerMask GroundLayer;
public int maxHealth = 3;
public int currentHealth;
bool isGrounded;
float moveInput;
Rigidbody2D rb2d;
float scaleX;
// Start is called before the first frame update
void Start()
{
healthBar.SetMaxHealth(maxHealth); //Sets healthbar to max health
currentHealth = maxHealth;
rb2d = GetComponent<Rigidbody2D>();
scaleX = transform.localScale.x;
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
if (currentHealth <= 0) //When Health is zero the player is destroyed
{
Destroy(gameObject);
}
healthBar.SetHealth(currentHealth); //Updates Healthbar when damgage is taken
}
// Update is called once per frame
void Update()
{
moveInput = Input.GetAxisRaw("Horizontal");
Jump();
}
private void FixedUpdate()
{
Move();
}
public void Move()
{
Flip();
rb2d.velocity = new Vector2(moveInput * moveSpeed, rb2d.velocity.y);
}
public void Flip()
{
if (moveInput > 0)
{
transform.localScale = new Vector3(scaleX, transform.localScale.y, transform.localScale.z);
}
if (moveInput < 0)
{
transform.localScale = new Vector3((-1) * scaleX, transform.localScale.y, transform.localScale.z);
}
}
public void Jump()
{
if (Input.GetKeyDown(KeyCode.Space))
{
CheckIfGrounded();
if (jumpsLeft > 0)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce);
jumpsLeft--;
}
}
}
public void CheckIfGrounded()
{
isGrounded = Physics2D.OverlapCircle(GroundCheck.position, GroundCheck.GetComponent<CircleCollider2D>().radius, GroundLayer);
ResetJumps();
}
public void ResetJumps()
{
if (isGrounded)
{
jumpsLeft = jumpsAmount;// jumpsAmount =2;
}
}
}
I put the groundcheck collider where the video wanted me to, even played around having different locations too. Nothing is working... tried changing the jump force too to see if it needs to be higher. I am at a complete loss.

Slow down player's speed in air

I am working on a 3D game currently that is based on Unity's Roll-a-Ball tutorial. The problem that I have encountered, is that whenever my player jumps, its speed increases in the air and I don't want that to happen. I tried coming up with a solution but I just couldn't make it work the way I wanted it to. How would I prevent this from happening?
Here is my code if anyone is interested:
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
private float movementX;
private float movementY;
public int count;
public GameObject player;
bool isGrounded = true;
public TextMeshProUGUI countText;
public GameObject winTextObject;
public float speed = 0;
public float jumpSpeed = 0;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winTextObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
void OnMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void Jump()
{
if (Input.GetKey(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector2.up * jumpSpeed, ForceMode.Impulse);
}
}
void FixedUpdate()
{
Jump();
Vector3 movement = new Vector3(movementX, 0f, movementY);
rb.AddForce(movement * speed);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("PickUp"))
{
other.gameObject.SetActive(false);
count++;
SetCountText();
}
}
void SetCountText()
{
countText.text = "Score: " + count.ToString();
if (count >= 14)
{
winTextObject.SetActive(true);
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
Debug.Log("You are colliding with the ground!");
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
Debug.Log("You are no longer grounded!");
}
}
}
Use drag to create air resistance:

How can I make it so when my player collides with an enemy, it disables movement input until player touches the ground?

So, I want to make it so the player loses control when it collides with an enemy. I already got a thing set up to make the player fly off towards the direction of the collision, but I can't seem to be able to make them lose control. I want input to not register.
Here's my player controller script:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Rigidbody2D _rigidBody2d;
Animator animatorController;
public float moveSpeed;
public float jumpForce = 1f;
float maxJumpHeight;
bool isOnGround = false;
bool collidedWithEnemy = false;
private void Start()
{
_rigidBody2d = GetComponent<Rigidbody2D>();
animatorController = GetComponent<Animator>();
}
float horizontalInput;
private void Update()
{
if (collidedWithEnemy == false)
{
horizontalInput = Input.GetAxis("Horizontal");
}
// Player movement
MovementMechanics();
// Sprite Flipping
SpriteFlipping();
// Jumping
JumpingMechanics();
// Set Falling Animation
FallingMechanics();
}
void MovementMechanics()
{
if (horizontalInput != 0)
{
transform.Translate(new Vector2(1, 0) * horizontalInput * Time.deltaTime * moveSpeed);
animatorController.SetBool("isMoving", true);
}
else
{
animatorController.SetBool("isMoving", false);
}
}
void SpriteFlipping()
{
if (horizontalInput > 0)
{
transform.localScale = new Vector3(-1, 1, 1);
}
else if (horizontalInput < 0)
{
transform.localScale = new Vector3(1, 1, 1);
}
}
void JumpingMechanics()
{
if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
{
_rigidBody2d.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
isOnGround = false;
animatorController.SetBool("isMoving", false);
animatorController.SetBool("isJumping", true);
animatorController.SetBool("isFalling", false);
}
}
void FallingMechanics()
{
if (_rigidBody2d.velocity.y < 0f)
{
animatorController.SetBool("isFalling", true);
}
else if (_rigidBody2d.velocity.y > 0f)
{
animatorController.SetBool("isFalling", false);
animatorController.SetBool("isJumping", true);
}
}
void OnCollisionEnter2D(Collision2D other)
{
// Avoids Jump Spawn
if (other.gameObject.CompareTag("Ground"))
{
isOnGround = true;
collidedWithEnemy = false;
animatorController.SetBool("isJumping", false);
animatorController.SetBool("isMoving", false);
animatorController.SetBool("isFalling", false);
}
// On Collision With Enemy
if (other.gameObject.CompareTag("Enemy"))
{
collidedWithEnemy = true;
}
}
}
And here's the enemy script:
using UnityEngine;
public class EnemyController : MonoBehaviour
{
Vector2 otherTransform;
Rigidbody2D playerRigidBody2d;
public float impulseForce = 100f;
private void Start()
{
playerRigidBody2d = GameObject.Find("Player").GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
otherTransform = other.gameObject.transform.position;
playerRigidBody2d.AddForce((otherTransform * 1) * impulseForce, ForceMode2D.Impulse);
other.transform.Translate(Vector3.zero);
}
}
}
And here's a little video of whats happening:
https://vimeo.com/709461296
As you can see in the console, the game still registers horizontal input after collision with enemy
(Don't mind the player launching off at lightspeed, thats not my concern here, I can fix that easily)
I'd say the problem is that you don't set horizontalInput to zero if the collision happens. The way you wrote your Update method, it takes the previously assigned value of horizontalInput and processes it.
Add the condition of not colliding with the enemy in MovementMechanics():
if (horizontalInput != 0 && !collidedWithEnemy)
{
// do something..
}

Is that a good usecase of delegates and events in Unity?

I just started learning Unity and wanna try to use events/delegates in FlappyBird game.
Flappy bird screenshot
As on this pic, I need to replace text with current score + 1, when the bird triggers collider between pipes.
public class BirdController : MonoBehaviour
{
private SpriteRenderer sr;
private Rigidbody2D rigidBody;
private Animator anim;
[SerializeField]
private float movementXForce, movementYForce, rotationSpeedUp,
rotationSpeedDown;
private float lastPosY;
float rotation;
private string FLY_ANIMATION = "fly";
private void Awake() {
sr = GetComponent<SpriteRenderer>();
rigidBody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
lastPosY = transform.position.y;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
fly();
moveRight();
animFly();
}
void fly()
{
if (Input.GetButtonDown("Jump")) {
rigidBody.AddForce(new Vector2(0f, movementYForce),
ForceMode2D.Impulse);
lastPosY = transform.position.y;
}
if (rigidBody.velocity.y < 0 && rigidBody.rotation > -30) {
rotation = -1f * rotationSpeedDown;
transform.Rotate(Vector3.forward * rotation);
} else if (rigidBody.velocity.y >= 0 && rigidBody.rotation < 30) {
rotation = 1f * rotationSpeedUp;
transform.Rotate(Vector3.forward * rotation);
}
}
void moveRight()
{
transform.position += new Vector3(1f, 0f, 0f) * Time.deltaTime *
movementXForce;
}
void animFly()
{
if (lastPosY < transform.position.y) {
anim.SetBool(FLY_ANIMATION, true);
} else {
anim.SetBool(FLY_ANIMATION, false);
}
}
private void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Ground") || other.CompareTag("Trap")) {
Destroy(gameObject);
}
}
private void OnTriggerExit2D(Collider2D other) {
if (other.CompareTag("Score")) {
}
}
}
I am about to add extra field in BirdController, something like
public delegate void OnTriggerScoreLine();
public static event OnTriggerScoreLine onTriggerScoreLine;
Then in OnTriggerExit2D I will
if (onTriggerScoreLine != null) {
OnTriggerScoreLine();
}
After that I will create new script ScoreController and there I will subscribe onTriggerScoreLine on method that will change the score text on score + 1 and also static scoreValue variable
And I just wanted to ask if I correctly understood delegates and events. Is it a good example of its using? Thanks:)

how can I make the game object disappear?

when I was watching on YouTube, tutorials about endless runner on part 2, the game object wouldn't disappear when it hits the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public int damage = 1;
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.GetComponent<rocket>().health -= damage;
Debug.Log(other.GetComponent<rocket>().health);
Destroy(gameObject);
}
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class rocket : MonoBehaviour
{
private Vector2 targetPos;
public float Yincrement;
public float speed;
public float maxHeight;
public float minHeight;
public int health = 3;
void Update()
{
if (health <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement);
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
}
}
}
from this one https://www.youtube.com/watch?v=FVCW5189evI and I'm confused why it didn't work, can someone tell me what is wrong?
if you want to destroy use this, Correct Method to get the game object when collide is: other.gameObject
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
Destory(other.gameObject);
}
}
public class megaStar : MonoBehaviour{
private Rigidbody2D rb;
private Animator _ani;
public bool canAttack = true;
[SerializeField] private Attack _attackObject;
private AudioSource _as;
public checkpoint lastCheckpoint;
public bool isDead = false;
private float _timer = 1.0f;
public float attackTimer = 2.0f;
public GameObject projectile;
public float projectileSpeed = 18.0f;
public Transform projectileAttackPoint;
public float timeDelayForNextShoot = 0.1f;
private float CONST_timeDelayForNextShoot;
// Start is called before the first frame update
void Start(){
CONST_timeDelayForNextShoot = timeDelayForNextShoot;
rb = GetComponent<Rigidbody2D>();
_as = GetComponent<AudioSource>();
_ani = GetComponent<Animator>();
_timer = attackTimer;
}
void Update(){
if (Input.GetKey(KeyCode.W))
{
rb.velocity = new Vector2(0f, 10f);
}
else if (Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector2(0f, -10f);
}
else
{
rb.velocity = new Vector2(0f, 0f);
}
timeDelayForNextShoot -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.K) && timeDelayForNextShoot <= 0f){
_ani.SetBool("projectileAttack", true);
GameObject go = Instantiate(projectile, projectileAttackPoint.position, projectileAttackPoint.rotation) as GameObject;
go.GetComponent<Rigidbody2D>().velocity = new Vector2(-projectileSpeed, 0.0f);
Destroy(go, 2.0f);
timeDelayForNextShoot = CONST_timeDelayForNextShoot;
canAttack = false;
// new WaitForSeconds(1);
return;
}
}
void FixedUpdate()
{
if (!isDead)
{
Update();
}
else{
rb.velocity = Vector2.zero;
RigidbodyConstraints2D newRB2D = RigidbodyConstraints2D.FreezePositionY;
rb.constraints = newRB2D;
}
}
private void OnCollisionEnter2D(Collision2D collision){
if (collision.gameObject.CompareTag("Enemy"))
{
GetComponent<HitPoints>().TakeDamage(1);
}
}
}
Use SetActive instead of Destroy Function.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
gameObject.SetActive(false);// it'll Hide GameObject instead of Destroying
// gameObject.SetActive(true);// to show again
}
}

Categories