Why does OnCollisionEnter2D not working? Unity - c#

I have an enemy prefab with and a bullet prefab with rigidbody2D and boxcolliders to both of them. I have made a TakeDamage function for the enemy when i made meelee combat and also a bullet shooting script. I made a simple OnCollisionEnter2D on the enemy(code is below) and they do collide and give the collision effect but the function doesn't work, it doesn't give any errors either... What do I do now?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public Transform player;
private Rigidbody2D rb;
[SerializeField] private SpriteRenderer sr;
private Vector2 movement;
public float moveSpeed = 5f;
public int maxHealth = 100;
int currentHealth;
Color32 colorRes = new Color32(255, 100, 50, 255);
public ParticleSystem deathParticles;
public GameObject projectile;
public int enemyDamage = 50;
public LayerMask rock;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
currentHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
sr.flipX = player.position.x - transform.position.x > 0;
Vector3 direction = player.position - transform.position;
direction.Normalize();
movement = direction;
}
private void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed));
}
public void TakeDamage()
{
currentHealth -= enemyDamage;
if(currentHealth <= 0)
{
Die();
}
StartCoroutine(BecomeRed());
}
void Die()
{
Instantiate(deathParticles, transform.position, Quaternion.identity);
Destroy(gameObject);
}
IEnumerator BecomeRed()
{
sr.color = colorRes;
yield return new WaitForSeconds(0.6f);
sr.color = Color.white;
}
void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log("test");
if (coll.gameObject.name == "rock")
{
TakeDamage();
Destroy(projectile);
}
}
}

Related

InvalidCastException: Specified cast is not valid (wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr). || Unity

InvalidCastException: Specified cast is not valid (wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr) || Unity
I'm trying to make a script for the enemy sprite to respawn when it is destroyed. This script does work for the most part as the sprite does respawn, however, its clone after its destroyed only has its Sprite Renderer component activated and it just gives me this error message:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
[Header("Health")]
[Header("Movement")]
[Header("Attack")]
[SerializeField] private float attackDamage = 10f;
[SerializeField] private float attackSpeed = 0.5f;
[SerializeField] private float maxHealth;
[SerializeField] private Transform respawnPoint;
public float speed = 3f;
public Transform trans;
private float canAttack;
private Transform target;
private float health;
public GameObject enemyObj;
Vector3 enemyPosition = new Vector3 (7.71339989f, -3.26340008f, 0f);
private void Start()
{
health = maxHealth;
}
public void TakeDamage(float dmg) {
health -= dmg;
Debug.Log("Enemy Health: " + health);
if (health <= 0)
{
speed = speed * 2f;
Destroy(gameObject);
StartCoroutine(Respawn());
}
}
private void Update()
{
if (target != null)
{
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target.position, step);
}
}
private void OnCollisionStay2D(Collision2D other)
{
if (other.gameObject.tag == "Player")
{
if(attackSpeed <= canAttack)
{
other.gameObject.GetComponent<General>().UpdateHealth(-attackDamage);
canAttack = 0f;
}
else
{
canAttack += Time.deltaTime;
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
target = other.transform;
}
}
IEnumerator Respawn()
{
enemyObj = (GameObject)Instantiate (enemyObj, enemyPosition, Quaternion.identity);
yield return null;
}
}

Double Jump in unity 2D and code optimization

I'm an absolute beginner in Unity and C# and I'm having some issues inserting a double jump on my Unity 2D Project. My question is: How can I be able to add a double jump on this code?
I tried to follow a lot of tutorials on internet, but I wasn't successful in any of the tutorials. This code I'm using right now is working normally, but I need to add the double jump function on the game.
Here's the code I'm using, I really need some help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rigidbody;
private BoxCollider2D collider;
private SpriteRenderer sprite;
private Animator animator;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
[SerializeField]private float PlayerMovementSpeed = 7f;
[SerializeField]private float PlayerJumpSpeed = 8f;
private enum MovementState { idle, running, jumping, falling }
// Start is called before the first frame update
private void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
collider = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
rigidbody.velocity = new Vector2(dirX * PlayerMovementSpeed, rigidbody.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
GetComponent<Rigidbody2D>().velocity = new Vector2(0, PlayerJumpSpeed);
}
UpdateAnimationState();
}
private void UpdateAnimationState()
{
MovementState state;
if (dirX > 0f)
{
state = MovementState.running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
state = MovementState.running;
sprite.flipX = true;
}
else
{
state = MovementState.idle;
}
if (rigidbody.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rigidbody.velocity.y < -.1f)
{
state = MovementState.falling;
}
animator.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(collider.bounds.center, collider.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}
The easy way to make this in your code is adding a counter of jumps, the variable starts in 0 and adds 1 to value on every jump, then you reset de variable when the character in on ground.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rigidbody;
private BoxCollider2D collider;
private SpriteRenderer sprite;
private Animator animator;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
[SerializeField]private float PlayerMovementSpeed = 7f;
[SerializeField]private float PlayerJumpSpeed = 8f;
private enum MovementState { idle, running, jumping, falling }
// NEW VARIABLE
private int jumpCounter;
// Start is called before the first frame update
private void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
collider = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
jumpCounter = 0;
}
// Update is called once per frame
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
rigidbody.velocity = new Vector2(dirX * PlayerMovementSpeed, rigidbody.velocity.y);
//THE CONDITION CHANGES
if (Input.GetButtonDown("Jump") && jumpCounter<2)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(0, PlayerJumpSpeed);
jumpCounter++;
}
if(IsGrounded())
{
jumpCounter = 0;
}
enter code here
UpdateAnimationState();
}
private void UpdateAnimationState()
{
MovementState state;
if (dirX > 0f)
{
state = MovementState.running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
state = MovementState.running;
sprite.flipX = true;
}
else
{
state = MovementState.idle;
}
if (rigidbody.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rigidbody.velocity.y < -.1f)
{
state = MovementState.falling;
}
animator.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(collider.bounds.center, collider.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}
EDIT:
Added a fix to the IsGrounded method.

Enemy Projectile Script Won't Shoot Closest Object

I Have been trying to figure out how the Enemy doesn't return multiple GameObjects it only returns one.Im not sure whether it is my Bullet script that it allows only one object to return. I'm currently trying to develop a Game with multiple players like Slither.io so I'm not sure if the performance is affected I would like to use (List Function) but dont know where to start and I'm using a later version Unity 2017.3.1f1. Much Appreciated for your help.The scripts are below.
public class RandomAIProjectile
{
private GameObject[] target;
public float speed;
Rigidbody2D bulletRB;
public GameObject explosionEffect;
// Find Targets Section.
void Start ()
{
if (target == null)
target = GameObject.FindGameObjectsWithTag("Player");
for (int i = 0; i < target.Length; i++)
{
bulletRB = GetComponent<Rigidbody2D> ();
Vector2 moveDir = (target[i].transform.position - transform.position).normalized * speed;
bulletRB.velocity = new Vector2 (moveDir.x, moveDir.y);
Destroy (this.gameObject, 2);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
// Decoy Script To Destroy Players.
if (other.gameObject.GetComponent<BlackthronpodDiePlayer>() != null)
{
Destroy (other.gameObject);
Destroy (gameObject);
}
// Damage Effect.
if (other.gameObject.tag == "Player") {
Instantiate (explosionEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
// Player (Bullet) Destroy Enemy.
if (other.CompareTag ("Bullet"))
{
Destroy (other.gameObject);
Destroy (gameObject);
}
}
}
Here is the Player Script
public class RandomAIEnemy
{
//Random Movement
public float speed;
public float waitTime;
public float startWaitTime;
public Transform moveSpots;
public float minX;
public float minY;
public float maxX;
public float maxY;
//Enemy AI Shooting
public float lineOfSite;
public float shootingRange;
public float fireRate = 1f;
private float nextFireTime;
public GameObject bullet;
public GameObject bulletParent;
// My Current Player
private BlackthronpodPlayerX playerX;
// Player AI
private GameObject[] player;
public GameObject blood;
Vector3 respawn = new Vector3 (-34f,0,0);
//Additional Info
void FixedUpdate ()
{
EnemyS ();
}
// Use this for initialization
void Start ()
{
//My Player AI Tag.
player = GameObject.FindGameObjectsWithTag("Player");
waitTime = startWaitTime;
//My Current Player Tag.
playerX = GameObject.FindGameObjectWithTag ("Player").GetComponent<BlackthronpodPlayerX>();
//Random Movement Reference
moveSpots.position = new Vector2 (Random.Range (minX, maxX), Random.Range (minY, maxY));
}
//Closest (My Player Including Player AI.)
private bool TryGetClosestPlayer(out GameObject closest)
{
var playersSortedByDistance = player.OrderBy(p => ((Vector2)p.transform.position - (Vector2)transform.position).sqrMagnitude);
closest = playersSortedByDistance.FirstOrDefault();
return closest;
}
void EnemyS ()
{
GameObject closestPlayer = null;
if(TryGetClosestPlayer (out closestPlayer))
{
var distanceFromPlayer = Vector2.Distance (closestPlayer.transform.position, transform.position);
if (distanceFromPlayer <= shootingRange && nextFireTime < Time.time)
{
Instantiate (bullet, bulletParent.transform.position, Quaternion.identity);
nextFireTime = Time.time + fireRate;
}
}
}
// Range And Shooting Boundary For Player Including Player AI.
private void OnDrawGizmosSelected ()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere (transform.position, lineOfSite);
Gizmos.DrawWireSphere (transform.position, shootingRange);
}
// Random Movement (I).
void RandomMove ()
{
//Rotate Movement Of Enemy.
transform.position = Vector2.MoveTowards (transform.position, moveSpots.position, speed * Time.deltaTime);
if (Vector2.Distance (transform.position, moveSpots.position) < 0.2f)
{
if(waitTime <= 0)
{
moveSpots.position = new Vector2 (Random.Range (minX, maxX), Random.Range (minY, maxY));
waitTime = startWaitTime;
} else {
waitTime -= Time.deltaTime;
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
// Damage Effect On Enemy.
if (collision.gameObject.tag.Equals ("Player"))
{
Instantiate(blood,transform.position, Quaternion.identity);
}
// My Players Health.
if (collision.CompareTag ("Player"))
{
playerX.health --;
Debug.Log(playerX.health);
Destroy(gameObject);
}
// Player Score Manager.
if (collision.tag == "Bullet")
{
Game.AddToScore(1);
Destroy(gameObject);
}
}
}
Make sure that you have Rigidbody2d attached on your enemy and player. And also, is there any error coming in the code?

How to make a shooting range for guns in unity2D?

I want my wepons to have a shooting range in my 2D game.For example if the bullet is out of range then destroy the bullet.Is it a problem if i don't use RayCast?
My script for the Wepon:
//Initialization
public GameObject Bullet;
public Transform FirePoint;
//WeponStats
public float BulletSpeed;
public int Damage;
public float Range;
private float TimeBtwShots;
public float StartTimeBtwShots;
private void Start()
{
}
private void Update()
{
if (TimeBtwShots <= 0)
{
if (Input.GetButton("Fire1"))
{
Shoot();
TimeBtwShots = StartTimeBtwShots;
}
}
else
{
TimeBtwShots -= Time.deltaTime;
}
}
void Shoot()
{
GameObject bullet2 = Instantiate(Bullet, FirePoint.position, FirePoint.rotation);
Rigidbody2D rb = bullet2.GetComponent<Rigidbody2D>();
rb.AddForce(FirePoint.right * BulletSpeed, ForceMode2D.Impulse);
}
And for the bullet:
public float Delay;
void Start()
{
Destroy(gameObject, Delay);
}
public void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Enemy"))
{ //take damage function, nothing important
Destroy(gameObject);
Wepon_Script script_W = GameObject.FindGameObjectWithTag("Wepon").GetComponent<Wepon_Script>(); //Wepon script
Enemy_Core script_E = GameObject.FindGameObjectWithTag("Enemy").GetComponent<Enemy_Core>(); //Enemy script
script_E.TakeDamage(script_W.Damage);
}
}
enter image description here
It seems you're already destroying the bullet after a delay:
Destroy(gameObject, Delay);
If you want the bullet to be destroyed after a distance traveled you could divide the distance by the speed.
Destroy(gameObject, Range / BulletSpeed);
If you want to measure dynamic distance traveled you could keep a track of it inside the bullet.
void FixedUpdate()
{
var distanceDelta = (transform.position - lastPos).magnitude;
distanceTravelled += distanceDelta;
lastPos = transform.position;
if (distanceTravelled > Range) Destroy(gameObject);
}

unity make moveable sprite clickable

I have a player sprite that moves anywhere on the screen clicked. I am trying to make a player info panel popup if the player sprite is clicked.
But unfortunately I only get the player moving a couple of pixels. I have a Box Collider 2d added to the sprite and an event trigger set to Pointer Click to run the method ShowPlayerInfoPanel
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
//Player Movement
float speed = 2f;
Vector2 targetPos;
private Rigidbody2D myRigidbody;
private Animator myAnim;
private static bool playerExists;
public static PlayerController instance;
public string exitPortal;
public bool startMoving;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
//Player Info
public string displayName;
public string coins;
//Player Panel display
public GameObject playerInfoPanel;
private void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
if(instance == null){
instance = this;
} else {
Destroy(gameObject);
}
DontDestroyOnLoad(transform.gameObject);
targetPos = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
startMoving = true;
}
if ((Vector2)transform.position != targetPos && startMoving)
{
Move();
} else {
myAnim.SetBool("PlayerMoving", false);
}
}
void Move()
{
Vector2 oldPos = transform.position;
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
//transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref velocity, smoothTime);
Vector2 movement = (Vector2)transform.position - oldPos;
myAnim.SetBool("PlayerMoving", true);
myAnim.SetFloat("Horizontal", movement.x);
myAnim.SetFloat("Vertical", movement.y);
}
public void ShowPlayerInfoPanel()
{
Debug.Log("hi");
PlayerInfoPanel playerInfo = playerInfoPanel.GetComponent<PlayerInfoPanel>();
playerInfo.DisplayName.text = displayName;
playerInfo.Coins.text = coins;
playerInfoPanel.SetActive(true);
}
}
With a collider on your gameObject you can just use OnMouseDown to detect when the object is clicked.
void OnMouseDown()
{
ShowPlayerInfoPanel();
}

Categories

Resources