How can I create a knockback effect on a specific point of a tilemap?

So I want to make these spikes and I’ve placed them using a tilemap since to make my level I need to place a lot of them and what I want to do is to make the player lose a certain amount of help when they touch the spike and then gets knocked back the opposite way from the point they made contact with the spike, so the specific point on the tilemap collider. I’ve done the health loss and it works but I can’t get the knockback effect to work properly. Here’s the code attached to the spikes:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpikesDamage : MonoBehaviour
{
    [SerializeField] private float dmg;

    public float knockbackForce;
    private Vector2 moveDirection;
    private GameObject player;

    private void Start() {
        player = GameObject.Find("Player");
    }

    private void OnTriggerEnter2D(Collider2D collider) {
        if (collider.gameObject.CompareTag("Player")) {
           
            collider.GetComponent<PlayerHealth>().TakeDamage(dmg);
            Rigidbody2D rb = collider.GetComponent<Rigidbody2D>();
            moveDirection = player.transform.position - collider.transform.position;
            collider.GetComponent<Rigidbody2D>().AddForce(moveDirection.normalized * 50000f);
        }
    }
}

Please help.

Usually when you have a player controller constantly controlling a player, you can’t do knockback: the moment you do the knockback, the controls immediately (or the next frame) stop the player from moving and it’s back to business as usual.

One solution is to use a timer (such as a float) that tracks how long the knockback effect is happening, and during the knockback, you specifically ignore the player’s input and let the knockback movement play out as the timer counts down.

private float knockBackHappening;

And then when you consider moving in Update():

if (knockBackHappening > 0)
{
  knockBackHappening -= Time.deltaTime;
}

if (knockBackHappening <= 0)
{
   // allow normal control here
}
else
{
   // do the knockback (or allow something else to do it)
}

The problem is not that. The issue is that if I create a new Vector2 and give it some value the knockback works however when I try to reference the position of the tilemap collider, no knockback happens. I’m guessing that’s because the tilemap itself doesn’t have a fixed position in the world but instead only a position on the grid so it probably returns a null value. So I’m wondering how I can fix that?

I think your problem is this line:

This script is on the spike, right? And it has a reference to the player? And it received (via the collider) an object that you verified (line 18) is the player …

So I think you’re subtracting the player’s position from the player’s position and getting zero. :slight_smile:

Perhaps you mean to use simply transform.position to represent the position of the spikes?

I tried using transform.position but what ends up happening is the player gets launched towards north-east every time no matter from what position they touch the spikes.

Then start printing things out, get data, figure out what is going on. Nobody here can do that… it’s your scene.

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, consider using Debug.DrawRay() or Debug.DrawLine() to visualize things like raycasts or distances.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

Ok thank you so much I’ll try that!