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

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:)

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 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
}
}

How to change default attack direction for player?

I coded my player in my platform game so that he would attack with a sword when you press space. It attacks right when I run right. It attacks left when I run left. But when I stand still by default it attacks left. How do I make it attack right instead?
Below is all the code in my player controller script, and also an image of my blend tree.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public int moveSpeed;
private Animator anim;
public int playerJumpPower = 1250;
private float moveX;
public bool isGrounded;
public float fJumpWaitTime = 0.2f;
private float fJumpWait;
private object col;
private bool attacking;
public float attackTime;
private float attackTimeCounter;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (!attacking)
{
if (Input.GetButtonDown("Jump"))
{
Jump();
}
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
{
transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
}
void Jump()
{
//Jumping Code
GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpPower);
isGrounded = false;
}
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("Player has collided with " + col.collider.name);
if (col.gameObject.tag == "ground")
{
isGrounded = true;
}
}
}
anim.SetFloat("MoveX", Input.GetAxisRaw("Horizontal"));
if (Input.GetKeyDown(KeyCode.Space))
{
attackTimeCounter = attackTime;
attacking = true;
anim.SetBool("Attack", true);
}
if(attackTimeCounter > 0)
{
attackTimeCounter -= Time.deltaTime;
}
if(attackTimeCounter <= 0)
{
attacking = false;
anim.SetBool("Attack", false);
}
}
}
After having another look at your Blend Tree, I would check if your Threst is the problem.
What you have right now:
PlayerAttackLeft 0 -1
PlayerAttackRight 1 1
What you should probably have:
PlayerAttackLeft -0.01 -1
PlayerAttackRight 0 1

Unity how to detect if a specific Game Object is near you

I'm creating a test game because I'm getting ready to create my first game but I want to make sure I get all the simple mechanics down that my first game will require. One of the mechanics that will be included in the game is picking up items if they are a certain distance to you. Sometimes there might be multiple of the same object in the game, I figured the code would work for all coins however that is just not the case. The Debug.Log() only works on one specific coin, how do I make it so it will fire no matter what coin I'm near?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
//Player Variables
public float moveSpeed;
public float jumpHeight;
public float raycastDistanceGround;
public Text moneyText;
private bool isGrounded;
private Rigidbody _rgb;
private GameObject player;
private GameObject[] coin;
private float distanceToCollectCoin;
private float distanceToCoin;
void Start () {
moveSpeed = 7f;
jumpHeight = 9f;
raycastDistanceGround = 0.5f;
isGrounded = true;
_rgb = GetComponent<Rigidbody>();
player = GameObject.FindGameObjectWithTag("Player");
coin = GameObject.FindGameObjectsWithTag("Coin");
distanceToCollectCoin = 2f;
Cursor.lockState = CursorLockMode.Locked;
}
void FixedUpdate () {
IsGrounding();
Move();
Jump();
SetMoneyText();
NearCoin();
}
//Player Moving Mechanics
void Move() {
var moveHorizontal = Input.GetAxis("Horizontal") * moveSpeed * Time.fixedDeltaTime;
var moveVertical = Input.GetAxis("Vertical") * moveSpeed * Time.fixedDeltaTime;
transform.Translate(moveHorizontal, 0f, moveVertical);
if (Input.GetKeyDown(KeyCode.Escape)) {
Cursor.lockState = CursorLockMode.None;
}
}
//Player Jump Mechanics
void Jump() {
var jump = new Vector3(0f, _rgb.position.y, 0f);
if (Input.GetKey(KeyCode.Space) && isGrounded == true) {
for (float i = 0; i <= jumpHeight; i++) {
jump.y += i;
_rgb.AddForce(jump);
}
}
}
void IsGrounding() {
if (Physics.Raycast(transform.position, Vector3.down, raycastDistanceGround)) {
isGrounded = true;
} else {
isGrounded = false;
}
}
void SetMoneyText() {
moneyText.text = ("Money: " + EconomyController.Money);
}
void NearCoin() {
for (int i = 0; i < coin.Length; i++) {
distanceToCoin = Vector3.Distance(coin[i].transform.position, player.transform.position);
}
if (distanceToCoin < distanceToCollectCoin) {
Debug.Log("Near Coin");
}
}
}
Looks like you just bracketed some stuff wrong. You need to move your if-statement into the for-loop. Right now it's only checking the distance for the last coin in the array.
void NearCoin()
{
for (int i = 0; i < coin.Length; i++)
{
distanceToCoin = Vector3.Distance(coin[i].transform.position, player.transform.position);
if (distanceToCoin < distanceToCollectCoin)
Debug.Log("Near Coin");
}
}

Categories