Hi guys im trying to make a game where you have to use the knockback of a shotgun to get around platformer levels and im haveing a bit of trouble with the knockback i feel like a ive done everething right but ill share my codes because it just doesnt seem to work idk if this is just the code or maybe something else but thankyou anyway
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerKnockback : MonoBehaviour
{
public float knockbackForce = 10f; // Strength of the knockback
private Rigidbody2D rb;
void Start()
{
// Get the Rigidbody2D component
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D is missing on the player object!");
}
}
void Update()
{
// Detect left mouse click to apply knockback
if (Input.GetMouseButtonDown(0))
{
ApplyKnockback();
}
}
void ApplyKnockback()
{
if (rb == null) return;
// Get the mouse position in world space
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0;
// Calculate the knockback direction (opposite to the direction from the player to the mouse)
Vector2 knockbackDirection = (transform.position - mousePosition).normalized;
// Apply the knockback force to the player's Rigidbody2D
rb.velocity = knockbackDirection * knockbackForce;
Debug.Log($"Knockback applied: Direction {knockbackDirection}, Force {knockbackDirection * knockbackForce}");
}
}
the player knockback
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShotgunRotation : MonoBehaviour
{
void Update()
{
// Get the world position of the mouse cursor
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
// Calculate the direction to the cursor
Vector3 direction = mousePos - transform.position;
// Rotate the shotgun to face the cursor
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
// Flip the shotgun based on the direction
Vector3 localScale = transform.localScale;
localScale.y = angle > 90 || angle < -90 ? -1 : 1;
transform.localScale = localScale;
}
}
the shotgun rotation
Thankyou
When something …
… that means you probably wrote a bug… and that means… time to start debugging!
By debugging you can find out exactly what your program is doing so you can fix it.
Use the above techniques to get the information you need in order to reason about what the problem is.
You can also use Debug.Log(...);
statements to find out if any of your code is even running. Don’t assume it is.
Once you understand what the problem is, you may begin to reason about a solution to the problem.
Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.
If you learn more by debugging and there is some specific thing that still seems mysterious…
How to report your problem productively in the Unity3D forums:
http://plbm.com/?p=220
This is the bare minimum of information to report:
- what you want
- what you tried
- what you expected to happen
- what actually happened, log output, variable values, and especially any errors you see
- links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)
The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?
If you post code, only post the relevant code and always use the format button above. Do not post photographs of code.
im not getting any errors so i dont know really what im trying to solve
You have an idea of what your code is supposed to do.
Now go figure out why that idea does not match reality.
Debugging helps you find out what your code is actually doing.
Debugging is not an optional step.
If you do NOT have an idea of what your code is doing, certainly none of us do either!!
Two steps to tutorials and / or example code:
- do them perfectly, to the letter (zero typos, including punctuation and capitalization)
- stop and understand each step to understand what is going on.
If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.
Imphenzia: How Did I Learn To Make Games:
I understand what im trying to solve and i have been trying to figure out what is going wrong but i cant figure it out i just wanted to know if anyone had any ideas of what it could be.
If they dont then im fine with that.
but thankyou for the response
It could perhaps be helpful if you drew out some Debug.DrawLine, for example between your mouseposition and your player character, see if that matches your expectations.
Print out the velocity you assign to the rigidbody (so save it in a local variable, print that, then assign it to the rigidbody), just to make sure that nothing weird happens and you get NaNs or zeros, or something. Perhaps you can debug.drawline the velocity as well, from your player character? That way you’ll more clearly see if the direction matches.
If you haven’t already tried that, try increasing the knockback factor by a few zeros. See if it is just a matter of too small force/velocity (this could possibly be done without any code changes/recompilations, hence why it’s a relevant suggestion)
This kind of implicit 3D to 2D can be the source of subtle issues for things where Z is not equal to zero, especially when normalisation is involved.
Use Vector2 for your “mousePosition”. Use “Rigidbody2D.position” as the player position because “transform.position” isn’t the authority (it’s not the same as the body position) if you’re using a Rigidbody2D with interpolation/extrapolation and it’s also a Vector3.
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 knockbackDirection = (rb.position - mousePosition).normalized;
I might’ve missed it but I don’t see any description of what “a bit of trouble” or “it just doesnt seem to work” means. You should describe what is happening or maybe post a video/images.
I can only presume that the “ShotgunRotation” is on a child GameObject and won’t be affecting the Rigidbody2D that PlayerKnockback is affecting.
Sorry I didn’t realise I hadn’t specified basically when I press the left mouse button which is what I set it to in the right direction it doesn’t actually move the player so to try and figure out what was happening I added some code to tell me if the player should be moving and where to move too and then when I ran it that would say that the player should be moving and yet it still wasn’t moving? Then I thought that the rigid body was not working but when I checked it seemed like it was. Also I have the player game object set as a parent to the shotgun which can follow the rotation of you mouse.
Sorry if this is confusing.
If a video would be more helpful the I can do that.
Thankyou
There could be lots of reasons it’s not moving so it’s impossible to say why so you need to narrow it down.
Narrow it down by trying things:
- Ensure you’re not setting the velocity elsewhere such as how you control the player movement. For instance, using “Rigidbody2D.MovePosition” constantly doesn’t ever use the body velocity, it’s Kinematic motion and you’d be asking it to constantly move to a position (velocity is useless in this case).
- Set the velocity Y to a crazy high value (+500) and it should shoot upwards
- Check the velocity you’re setting is the correct direction and isn’t moving into a surface with no bounce therefore doing nothing
- Increase the “knockbackForce” (which isn’t a force btw, it’s a speed)
- Check the Vector2/Vector3 stuff I mentioned.
Note that physics doesn’t run per-frame either so no idea what else you could be doing before the FixedUpdate runs. Unless you’ve changed physics to run per-frame.
Ok I’ll try this thankyou do you think that haveing a movement script which also affects the velocity could effect it?
Of course, yes. You cannot have two different velocities, that would make no sense.
This is why writing directly to the velocity is dangerous because it completely stomps over any previous velocity you set along with any forces being applied, gravity etc. It’s the reason why adding forces or impulses exist because they add-up.
Sounds like you need to stop applying movement (writing to the velocity) while you’re doing the “knockback”.
1 Like