Hello i am making a 2d game and I have a player that needs to collide with 2 objects. First object gives him more health and has the tag " power up " and works but the second that has the tag " Hurt" it's not working . What I should change in the script ? Here it's the script for " PowerUp" and here it's the script of the player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PowerUpDetector : MonoBehaviourPun
{
// reference this via the Inspector
[SerializeField] private Character healthbar;
[SerializeField] private Character health;
private void Awake()
{
if (!healthbar) healthbar = GetComponent<Character>();
}
private void OnTriggerEnter2D(Collider2D other)
{
// or whatever tag your powerups have
if (!other.CompareTag("PowerUp"))
{
Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
return;
}
var powerup = other.GetComponent<PowerUp>();
if (!powerup)
{
Debug.LogError($"Object {other.name} is tagged PowerUp but has no PowerUp component attached", this);
return;
}
Debug.Log("Found powerup, pick it up!", this);
powerup.Pickup(healthbar);
if (!other.CompareTag("Hurt"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
}
}
[PunRPC]
void Damage()
{
health -= 20;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using Photon.Pun;
using Photon.Realtime;
using Photon;
using UnityEngine.UI;
public class Character : MonoBehaviourPun,IPunObservable
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 400f, bulletSpeed = 500f;
[SerializeField] private float health = 100;
[SerializeField] private Slider slider;
[SerializeField] private Gradient gradient;
[SerializeField] private Image fill;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
if (photonView.IsMine)
{
}
else
{
}
}
public float Health
{
get { return health; }
set
{
health = value;
slider.value = health;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
private void OnCollisionEntered2D(Collision2D col)
{
if( col.gameObject.CompareTag ("Hurt"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
}
}
[PunRPC]
void Damage()
{
health -= 20;
}
// Update is called once per frame
void Update()
{
if (photonView.IsMine)
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX != 0)
{
barrel.up = Vector3.right * Mathf.Sign(dirX);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
else
{
}
}
void FixedUpdate()
{
if (photonView.IsMine)
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
}
void Jump()
{
if (photonView.IsMine)
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
}
void Fire()
{
if (photonView.IsMine)
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
stream.SendNext(health);
}else if (stream.IsReading)
{
health = (float)stream.ReceiveNext();
}
}
public void SetMaxHealth(int value)
{
if (photonView.IsMine)
{
slider.maxValue = value;
// The property handles the rest anyway
Health = value;
}
}
}
I have an error in the "Power Up Detector" at health -= 20 (operator -= can't be applied ) to operands type "Character" and " int" .
I think you will have to use health.Health. Your variable health refers to the Character class. As you want to change the health, you would have to use the property of that class instead. So try:
health.Health -= 20;
I would recommend to rename the health variable to something else related to the Character class though.
Related
Here's my code for player movement. I have set up walking around and I am now Trying to change the sprite animation when walking in different directions. Everything was working fine but when I tried to change the sprite for walking up the sprite gets stuck in a loop and doesn't idle.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Animator Animator;
[SerializeField] private float speed = 1f;
private Rigidbody2D body;
private Vector2 axisMovement;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
axisMovement.x = Input.GetAxisRaw("Horizontal");
axisMovement.y = Input.GetAxisRaw("Vertical");
Animator.SetFloat("Speed", Mathf.Abs(axisMovement.x));
if (Input.GetKey(KeyCode.W))
{
Animator.SetBool("isforward", true);
}
if (Input.GetKey(KeyCode.A))
{
Animator.SetBool("isforward", false);
}
if (Input.GetKey(KeyCode.S))
{
Animator.SetBool("isforward", false);
}
if (Input.GetKey(KeyCode.D))
{
Animator.SetBool("isforward", false);
}
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
body.velocity = axisMovement.normalized * speed;
CheckForFlipping();
}
private void CheckForFlipping()
{
bool movingLeft = axisMovement.x < 0;
bool movingRight = axisMovement.x > 0;
if (movingLeft)
{
transform.localScale = new Vector3(-1f, transform.localScale.y);
}
if (movingRight)
{
transform.localScale = new Vector3(1f, transform.localScale.y);
}
}
}
I also tried doing Animator.SetFloat("Speed", Mathf.Abs(axisMovement.x)); but switch it with axisMovement.y but that stops all the animations moving left and right stop working. 😢
I've figured it out. here's the updated code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Animator Animator;
[SerializeField] private float speed = 1f;
private Rigidbody2D body;
private Vector2 axisMovement;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
axisMovement.x = Input.GetAxisRaw("Horizontal");
axisMovement.y = Input.GetAxisRaw("Vertical");
Animator.SetFloat("Speed", Mathf.Abs(axisMovement.x + axisMovement.y));
if (Input.GetKey(KeyCode.W))
{
Animator.SetBool("isforward", true);
} else {
Animator.SetBool("isforward", false);
}
// if (Input.GetKey(KeyCode.A))
// {
// Animator.SetBool("isforward", false);
// }
// if (Input.GetKey(KeyCode.S))
// {
// Animator.SetBool("isforward", false);
// }
// if (Input.GetKey(KeyCode.D))
// {
// Animator.SetBool("isforward", false);
// }
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
body.velocity = axisMovement.normalized * speed;
CheckForFlipping();
}
private void CheckForFlipping()
{
bool movingLeft = axisMovement.x < 0;
bool movingRight = axisMovement.x > 0;
if (movingLeft)
{
transform.localScale = new Vector3(-1f, transform.localScale.y);
}
if (movingRight)
{
transform.localScale = new Vector3(1f, transform.localScale.y);
}
}
}
When creating the game, I came across the problem that after adding animation to the player's code in the play mode, he stopped moving.
I did everything as usual, went into the animator, made an animation, and then set up and added everything necessary to the code in the animator, but after that the player stopped moving although before that everything was fine.
Help me, I hope it's not difficult.
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Controlled player")]
public Rigidbody2D rb;
[Header("Tinctures of movement")]
public float PSpeed = 1f;
public float jumpForce = 1f;
[Header("Variable Reduction parameters")]
public float LowingPSPeed;
public float FormedPSpeed;
[Header("Traffic Statuses")]
public bool Move;
public bool Jump;
[Header("")]
[Header("Checking the ground under the player")]
public bool OnGround;
private bool doJump = false;
private bool GOright = false;
private bool GOleft = false;
[Header("Ground Check Settings")]
private float groundRadius = 0.3f;
public Transform groundCheck;
public LayerMask groundMask;
private Animator anim;
void Math()
{
FormedPSpeed = PSpeed / LowingPSPeed;
}
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
Math();
if (Input.GetKeyDown(KeyCode.Space))
{
doJump = true;
}
if (Input.GetKey("d"))
{
GOright = true;
}else
{
GOright = false;
}
if (Input.GetKey("a"))
{
GOleft = true;
}
else
{
GOleft = false;
}
}
void FixedUpdate()
{
OnGround = Physics2D.OverlapCircle(groundCheck.position, groundRadius, groundMask);
if (GOright && Move)
{
transform.position += new Vector3(FormedPSpeed, 0, 0);
GetComponent<SpriteRenderer>().flipX = false;
}
if (GOleft && Move)
{
transform.position += new Vector3(-(FormedPSpeed), 0, 0);
GetComponent<SpriteRenderer>().flipX = true;
}
if (doJump && Jump && OnGround)
{
rb.AddForce(new Vector2(0, (jumpForce * 10)));
anim.SetTrigger("takeOf");
doJump = false;
}
if (OnGround)
{
anim.SetBool("isJump", false);
}else
{
anim.SetBool("isJump", true);
}
if (!GOleft && !GOright)
{
anim.SetBool("isRun", false);
}else
{
anim.SetBool("isRun", true);
}
}
I don't understand why this is happening
https://drive.google.com/file/d/1Uc2sys7ZFd686UkQlYAMEDZekFEHZcAr/view?usp=sharing
as u see in the video when I try to jump from the mountain the player just goes through the terrain as if it's not there but I can still move normal and I noticed that whenever I move fast while being off the ground the problem appears like when I first started this level I was jumping and returning to the ground very slowly and whenever I jump and move fast towards a hell the problem occurs so I increased the gravity so that I can't move while jumping but still if I move fast while in the air the player won't collide with the terrain but when I move normally or fast on the ground non of that happen's can anyone help me?
I searched on the internet and I found nothing related to this.
terrain 1 properties:
https://drive.google.com/file/d/1VwelecESLjfD7UseP6lmQ0Kkg-3pwg67/view?usp=sharing
terrain 2 properties:
https://drive.google.com/file/d/1ZH-cIBXlhBMPbmkgZXkQmjt-QVpe6MLu/view?usp=sharing
player properties:
https://drive.google.com/file/d/1vTp3TSuIDcYm3orWhy5X3kw6wwBmwNcE/view?usp=sharing
here are the codes used for this:
mouse lock:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouselock : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
player movement:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class playermove2 : MonoBehaviour
{
[Header("movement")]
private float movespeed = 10f;
[SerializeField] float airmultiplier = 0.4f;
[SerializeField] Transform oriantation;
private float horizontalmovement;
private float verticalmovement;
private float rbdrag = 6f;
private Vector3 movedirection;
public float movementmultiplier = 10f;
public bool isgrounded;
private float playerhight = 1.8f;
public float jumpforce = 8;
public Rigidbody rb;
public float grounddrag = 6f;
public float aridrag = 2f;
public int number;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (number == 11)
{
SceneManager.LoadScene("finish scene2");
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
movespeed = 25;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
movespeed = 20;
}
if (Input.GetKeyDown(KeyCode.Space) && isgrounded)
{
jump();
}
print(isgrounded);
myinput();
controledrag();
}
private void myinput()
{
horizontalmovement = Input.GetAxisRaw("Horizontal");
verticalmovement = Input.GetAxisRaw("Vertical");
movedirection = oriantation.forward * verticalmovement + oriantation.right * horizontalmovement;
}
private void FixedUpdate()
{
moveplayer();
}
void moveplayer()
{
if (isgrounded)
{
rb.AddForce(movedirection.normalized * movespeed * movementmultiplier, ForceMode.Acceleration);
}
else
{
rb.AddForce(movedirection.normalized * movespeed * movementmultiplier * airmultiplier, ForceMode.Acceleration);
}
}
void controledrag()
{
if (isgrounded)
{
rb.drag = grounddrag;
}
else
{
rb.drag = aridrag;
}
}
void jump()
{
rb.AddForce(transform.up * jumpforce, ForceMode.Impulse);
}
}
collisions:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collisions2 : MonoBehaviour
{
public playermove2 player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.layer == 6)
{
player.isgrounded = true;
}
}
private void OnCollisionExit(Collision other)
{
if (other.gameObject.layer == 6)
{
player.isgrounded = false;
}
}
}
camera movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCamera : MonoBehaviour
{
[SerializeField] Transform cameraposition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = cameraposition.position;
}
}
player look:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerlook : MonoBehaviour
{
[SerializeField] private float sensX;
[SerializeField] private float sensY;
[SerializeField] Transform cam;
[SerializeField] Transform oriantation;
private float mouseX;
private float mouseY;
private float multiplier = 0.01f;
private float xRotation;
private float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
yRotation += mouseX * sensX * multiplier;
xRotation -= mouseY * sensY * multiplier;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
oriantation.transform.rotation = Quaternion.Euler( 0, yRotation, 0);
}
}
triggers:
using UnityEngine;
using UnityEngine.SceneManagement;
public class triggers2 : MonoBehaviour
{
public playermove2 playerMove;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 8)
{
Destroy(other.gameObject);
playerMove.number++;
}
}
}
score and high score:
using UnityEngine;
using UnityEngine.UI;
public class scoreandhighscore2 : MonoBehaviour
{
public Text highscoretext;
public Text scoretext;
public playermove2 playermove;
// Start is called before the first frame update
void Start()
{
highscoretext.text = "high score: " + PlayerPrefs.GetInt("highscore");
}
// Update is called once per frame
void Update()
{
scoretext.text = "score: " + playermove.number.ToString();
}
private void FixedUpdate()
{
if ( playermove.number > PlayerPrefs.GetInt("highscore"))
{
PlayerPrefs.SetInt("highscore", playermove.number);
}
}
}
sooooo I solved the problem the solution is just converting the collision detection to continuous and just like that the player won't break through the terrain I hope this is helpful for other people
here's a pic of what I did:
https://drive.google.com/file/d/1ati8xQFQxwqAg8eJnmZzrs8D05HGuJLs/view?usp=sharing
I'm making a multiplayer game2d and when my player shoots (the gun has a collider too )it's affecting his life and I don't know why.Probably because when the target "hurt" has RPCtarget.all but I don't know with what to change just to affect the others players in the game , not mine. With what I can replace all?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using Photon.Pun;
using Photon.Realtime;
using Photon;
using UnityEngine.UI;
public class Character : MonoBehaviourPun,IPunObservable
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 400f, bulletSpeed = 500f;
[SerializeField] private float health = 100;
[SerializeField] private Slider slider;
[SerializeField] private Gradient gradient;
[SerializeField] private Image fill;
public Rigidbody2D bulletPrefabs;
Vector3 localScale;
public DeathsCount myCounts;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
if (photonView.IsMine)
{
myCounts = FindObjectOfType<DeathsCount>();
}
else
{
}
}
public float Health
{
get { return health; }
set
{
health = value;
slider.value = health;
// fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("Hurt"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
}
if (col.gameObject.tag == "PowerUp")
{
if (photonView.IsMine)
{
var powerup = col.GetComponent<PowerUp>();
powerup.Pickup(this);
}
else
{
}
}
if (col.gameObject.CompareTag("Bullet"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
bullet = bulletPrefabs;
}
}
else
{
}
}
[PunRPC]
void Damage()
{
if (Health > 0)
{
Health -= 20;
}
if (Health <= 0) // check health status
{
Health = 0; // make that Heath don't be < 0
if (photonView.IsMine)
{
myCounts.RpcRespawn(); //Here you should to call counter
photonView.transform.position = Vector2.zero;
Health = 100;
}
}
}
// Update is called once per frame
void Update()
{
if (photonView.IsMine)
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX != 0)
{
barrel.up = Vector3.right * Mathf.Sign(dirX);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
else
{
}
}
void FixedUpdate()
{
if (photonView.IsMine)
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
}
void Jump()
{
if (photonView.IsMine)
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
}
void Fire()
{
var firedBullet = PhotonNetwork.Instantiate(bullet.name, barrel.position, barrel.rotation).GetComponent<Rigidbody2D>();
firedBullet.AddForce(barrel.up * bulletSpeed);
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
stream.SendNext(Health);
}
else if (stream.IsReading)
{
Health = (float)stream.ReceiveNext();
}
}
public void SetMaxHealth(int value)
{
if (photonView.IsMine)
{
slider.maxValue = value;
// The property handles the rest anyway
Health = value;
}
}
}
I think you don't really need RPC in this case.
I see your character IPunObservable and, I guess, added to PhotonView. So its health will sync automatically.
You also instantiate bullets with PhotonNetwork, which means, they will sync too and have PhotonView.
So every player has all synchronized bullets and other players.
It means, all that you need is to check if bullet is from other player and set damage locally (don't worry, result will sync) like this :
. . .
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("Hurt"))
{
// if hurt object is not mine, take damage
if (!col.gameObject.GetPhotonView().isMine)
Damage();
}
if (col.gameObject.tag == "PowerUp")
{
if (photonView.IsMine)
{
var powerup = col.GetComponent<PowerUp>();
powerup.Pickup(this);
}
else
{
}
}
if (col.gameObject.CompareTag("Bullet"))
{
// if bullet is not mine, take damage
if (!col.gameObject.GetPhotonView().isMine)
Damage();
}
else
{
}
}
// no rpc
void Damage()
{
if (!photonView.IsMine) // only player can change his life
return;
if (Health > 0)
{
Health -= 20;
}
if (Health <= 0) // check health status
{
myCounts.RpcRespawn(); //Here you should to call counter
photonView.transform.position = Vector2.zero;
Health = 100;
}
}
I am doing a 2d game and my player collides with 2 different objects. One it's for gaining health and the other one it's for damage it. So I have two tags : PowerUp( and this one works) and Hurt( I get in the console a message like this and I don't understand why : Registered a collision but with wrong tag: Hurt ) This is the script that I used, what I should change at it for this action of DAMAGE to take place ( and I tried on collision entered too)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PowerUpDetector : MonoBehaviourPun
{
// reference this via the Inspector
[SerializeField] private Character healthbar;
[SerializeField] private Character health;
private void Awake()
{
if (!healthbar) healthbar = GetComponent<Character>();
}
private void OnTriggerEnter2D(Collider2D other)
{
// or whatever tag your powerups have
if (!other.CompareTag("PowerUp"))
{
Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
return;
}
var powerup = other.GetComponent<PowerUp>();
if (!powerup)
{
Debug.LogError($"Object {other.name} is tagged PowerUp but has no PowerUp component attached", this);
return;
}
Debug.Log("Found powerup, pick it up!", this);
powerup.Pickup(healthbar);
if (!other.CompareTag("Hurt"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
}
}
[PunRPC]
void Damage()
{
health.Health -= 20;
}
}
Option 2 same error enter image description here
private void OnCollisionEntered2D(Collision2D col)
{
if( col.gameObject.CompareTag ("Hurt"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
}
}
[PunRPC]
void Damage()
{
health -= 20;
}
My players script with the healthbar
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using Photon.Pun;
using Photon.Realtime;
using Photon;
using UnityEngine.UI;
public class Character : MonoBehaviourPun,IPunObservable
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 400f, bulletSpeed = 500f;
[SerializeField] private float health = 100;
[SerializeField] private Slider slider;
[SerializeField] private Gradient gradient;
[SerializeField] private Image fill;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
if (photonView.IsMine)
{
}
else
{
}
}
public float Health
{
get { return health; }
set
{
health = value;
slider.value = health;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
/* private void OnCollisionEntered2D(Collision2D col)
{
if( col.gameObject.CompareTag ("Hurt"))
{
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
}
}
[PunRPC]
void Damage()
{
health -= 20;
}*/
// Update is called once per frame
void Update()
{
if (photonView.IsMine)
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX != 0)
{
barrel.up = Vector3.right * Mathf.Sign(dirX);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
else
{
}
}
void FixedUpdate()
{
if (photonView.IsMine)
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
}
void Jump()
{
if (photonView.IsMine)
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
}
void Fire()
{
if (photonView.IsMine)
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
stream.SendNext(health);
}else if (stream.IsReading)
{
health = (float)stream.ReceiveNext();
}
}
public void SetMaxHealth(int value)
{
if (photonView.IsMine)
{
slider.maxValue = value;
// The property handles the rest anyway
Health = value;
}
}
}
// or whatever tag your powerups have
if (!other.CompareTag("PowerUp")) {
Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
return;
}
This statement will log an error whenever you collide with something that is not tagged "PowerUp" (I.E. if it's tagged "Hurt").
The return statement then boots you out of the function and that means it does not get to the part where it deals damage.
You may want to change this to include && !other.CompareTag("Hurt") to the if statement. A better approach may be to remove this if statement entirely. You should be checking tags like this :
if(has this tag) {
Do this
}
if(has that tag) {
Do that
}
Instead of seeing if it doesn't have the tag and returning.
Something like this, see below. But please read the comment related to the "Hurt" tag. Wrote it in this text editor, but I think syntax is correct.
private void OnTriggerEnter2D(Collider2D other)
{
switch (other.tag)
{
case "PowerUp":
var powerup = other.GetComponent<PowerUp>();
powerup.Pickup(healthbar);
break;
// You use '!other.CompareTag("Hurt")'. So you check if the tag is NOT hurt? Is that correct? I would assume you would check to see if it IS 'Hurt'?
case "Hurt":
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.All);
}
break;
default:
Debug.Log("did not recognize this tag:" + other.tag);
break;
}
}