I’m making a game where my first Enemy is one that acts exactly like a goomba from Mario Bros, I have implemented a Raycast and made it so that if the player jumps on the Enemy you shoot up in the air and the Enemy disappears, but the problem is that the Enemy just disappears without the player getting flung into the air.
Here’s my code. The script is attached to the player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Squishie : MonoBehaviour {
// Update is called once per frame
void Update () {
PlayerRaycast();
}
void PlayerRaycast () {
RaycastHit2D hit = Physics2D.Raycast (transform.position, Vector2.down);
if( hit.collider != null )
{
Debug.LogFormat( "Something has been hit: {0} ({1} units away)", hit.collider.tag, hit.distance );
if (hit.distance < 1.3f && hit.collider.tag == "Enemy") {
Debug.Log ("Eyyy");
GetComponent<Rigidbody2D> ().AddForce (Vector2.up * 500);
Destroy (hit.collider.gameObject);
}
}
}
}
I have tested this in a sample project and it works. I have added some optimisations also.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Squishie : MonoBehaviour
{
//so that you can adjust the raycast position easily
public Transform raycastPoint;
//change form inspector
[SerializeField]
private int playerDownwardsRaycastDistance = 1;
//change form inspector
[SerializeField]
private int upwardsForceOnPlayer = 500;
private Rigidbody2D playerRigidBody2D;
private int enemyLayerID;
void Start()
{
//to optimize the raycast
//the raycast will only check for the Enemy colliders only
//do not forget to make a layer named "Enemy" and set this layer for all enemies
enemyLayerID |= 1<< LayerMask.NameToLayer("Enemy");
//cache the component
playerRigidBody2D = GetComponent<Rigidbody2D>();
}
void Update ()
{
PlayerRaycast();
}
void PlayerRaycast ()
{
/*
* Optimised raycast as
* 1) Only checks for playerDownwardsRaycastDistance = 1 , i.e. only 1 unit distance
* 2) Only checks for enemy colliders
*/
RaycastHit2D hit = Physics2D.Raycast (raycastPoint.position , Vector2.down , playerDownwardsRaycastDistance , enemyLayerID);
if( hit.collider != null )
{
//to check where your raycast is going
//Debug.DrawRay(raycastPoint.position , Vector2.down , Color.red , 2);
//******** i have changed your tag name*********
if ( hit.collider.tag == "Goomba")
{
Debug.Log ("Eyyy");
playerRigidBody2D.AddForce (Vector2.up * upwardsForceOnPlayer);
Destroy (hit.collider.gameObject);
}
}
}
}