Launch you backwards

Hey! I’m making a game, and I’ve made shooting, but I wanna make my gun boost you the opposite way you are looking, but honestly, I don’t know where to start.

Here’s my blank canvas so far, lol

public gameObject cam;
public gameObject Player;

void Shoot() {
}

So inside of Shoot() I want to boost the object (Player) the opposite way of the Camera’s (cam) rotation

please explain what does shooting have to do with camera rotation?
you obviously just want a reactionary force from the gun, why are you suddenly mingling stuff that has nothing to do with it?

and ok, maybe you’re just mixing stuff together, because you’re considering the way the player is looking, so camera comes to you as a logical piece of this puzzle, but let’s start from the beginning. first off, I will assume you’re doing a 3D game, from the sound of it.

no, you absolutely don’t need a camera (I mean, for the logic of reactive shooting). but ok, we can use a camera as a state holder, if you’d like – the state being the looking direction. be mindful that you could just as well keep this state completely independently of any camera, and then update the camera to reflect this – just saying.

okay, so you keep the camera together with the player, it’s best to nest it then in the hierarchy, keep it as a child of player. when you shoot, you instantiate a bullet, assign it a forward vector, and some other parameters, maybe slight deviation in trajectory, maybe you give it a color, maybe a lifetime, hit points, all that jazz, and finally velocity. the prefab you use for a bullet has a script on it, so we don’t care about the bullet in this code, we only care about its kickback, right?

well, it’s very simple. the kickback of the bullet is a force that acts opposite to its velocity, and should be relatively small-ish because the mass of the bullet is many times smaller than the mass of the player. but if you want the game to possess an arcade flavor, you could make the strength of this force configurable.

let’s assume you have a working character controller, to start off with something.
Unity’s standard character controller comes with several features: mouse look, WASD, ground detection, jumping, and slippery contact to avoid getting stuck into walls and low ceilings, if I remember correctly.

to instantiate a bullet (I’d recommend reusing a prefab from a pool) you do something like this in player’s class

void Shoot() {
  MyBullet bullet = GameObject.Instantiate(...).GetComponent<MyBullet>(); // position, rotation, etc go here
  bullet.ConfigureAndRun(...); // other parameters go here, including velocity
}

then you have the bullet itself

using System;
using UnityEngine;

public class MyBullet : MonoBehaviour {
 
  [NonSerialized] public int index;
  [NonSerialized] public int hitPoints;
  [NonSerialized] public Color color;
  [NonSerialized] public Vector3 direction;
  [NonSerialized] public float lifetime;
  [NonSerialized] public float velocity;

  public void ConfigureAndRun(int index, Vector3 direction, float velocity, float lifetime, int hp, Color color) {
    this.index = index; // this is only for book-keeping, especially if reused from a pool of several pre-instantiated bullets
    this.hitPoints = hp;
    this.color = color;
    this.direction = direction;
    this.lifetime = lifetime;
    this.velocity = velocity;
    enabled = true;
  }

  void Update() {
    transform.localPosition += velocity * direction * Time.deltaTime;
    lifetime -= Time.deltaTime;
    if(lifetime <= 0f) Kill();
  }

  // you need some OnCollision functions, as usual, to register hitting enemies and walls

  public void Kill() {
    enabled = false;
    GameObject.Destroy(this.gameObject);
  }

}

Now we can flesh out Shoot in Player with more stuff

using UnityEngine;

public class Player : MonoBehaviour {

  [SerializeField] GameObject myBulletPrefab;
  [SerializeField] [Range(0f, 20f)] float kickbackStrength = 10f;
  [SerializeField] [Range(0f, .98f)] float kickbackDampening = 0.976f;
  Vector3 _kickback;

  public void Shoot(float kickbackStrength) {

    // first you come up with the exact direction in which the player is shooting
    // you want to keep this
    var shootingDirection = deviateFromDirection(
      origin: transform.position,
      dir: transform.forward,
      distance: 1f,
      radius: 0.2f
    );

    // this object should not be parented to anything
    // you need to make a bullet prefab that has MyBullet attached to it
    // then link that prefab to 'myBulletPrefab' in the inspector
    MyBullet bullet = GameObject.Instantiate(
      original: myBulletPrefab,
      position: transform.position,
      rotation: transform.forward // (this isn't entirely true, but let's roll with this for now)
    ).GetComponent<MyBullet>();

    bullet.ConfigureAndRun(
      index: 0,
      direction: shootingDirection, // now we send this to the bullet, to make it travel the right path
      velocity: 10f,
      lifetime: 5f,
      hp: 10,
      color: Color.red
    );

    // finally, you apply this direction as a force that affects the player
    // for this we use _kickback vector as an accumulator
    _kickback -= shootingDirection * kickbackStrength; // notice the minus, this is because kickbacks go in the opposite direction
  }

  // imagine a small circular target in front of the player, it is at some distance and has a radius
  // the bullet path will randomly deviate from the center so that it always lands within this circle
  // if you intend to have more than 5 bullets per frame coming off from multiple agents, then
  // this can be made significantly faster, but in the general case this will suffice (it's still fast)
  Vector3 deviateFromDirection(Vector3 origin, Vector3 dir, float distance, float radius) {
    var c = origin + distance * dir;
    var q = Quaternion.FromToRotation(Vector3.back, dir);
    var p = c + q * (Vector3)(radius * Random.insideUnitCircle);
    return (p - origin).normalized;
  }

}

Now, alongside the usual stuff associated with character controller you additionally process this kickback in the Player’s update

void Update() {
  _kickback *= kickbackDampening; // a cheap trick to progressively diminish this "force" until it's almost zero (keep it sufficiently larger than 0, but never at 1 or more)
  transform.localPosition += _kickback * Time.deltaTime;

  // regular player control goes here
  // depending on where exactly you capture user input, you want to call Shoot() when some button is pressed
}

If you’ve made the standard shooting stuff before, hopefully this is enough to get you started.

(I’m also sure I’ve made an error somewhere and you’ll probably have to tweak the values until it resembles something of use, but the concept is here.)

(You also need to make some sort of shooting cooldown so that you can’t launch gazillion bullets with a short hold of a button)

2 Likes

The camera has to do with the way you are looking, I want to boost you, the OPPOSITE, way you are looking, and you need to find the location you are looking

Also the problem is, I don’t use an actual bullet, I just use a raycast as a viable solution & add some effects

Also, you seem to be over complicating this, adding all the kill and stuff, I’ve already done that, what I want, is just to know how to boost an object the opposite way of one objects rotation, eg, the camera is looking down, you get boosted up, the camera is looking forwards, you get boosted backwards, and so on and so on

I’m just honestly so confused why you are walking me thru creating a gun instead of specifically only what I’ve asked, kicking the player back, the opposite way its looking, I mean, I’ve said, I already made a gun

Add a Rigidbody to your player. Get the forward vector of the camera. Reverse it. Add an ForceMode.Impulse force in the reversed camera forward direction to the player rigidbody (multiplied by some value for increased effect). Done.
If you dont want to use a Rigidbody but instead manage your own velocity vector, simply add to that instead. If you dont use a Rigidbody or keep track of your own velocity vector for movement… then… do that instead.

1 Like

I’m sorry, I’m not exactly a unity expert, so I don’t know how to do all that, my player already has a rigid body, so how do I get the forward vector in a script, also how do I use ForceMode.Impulse in a script… Thanks if I don’t ask these questions I’d probably never get it, lol

I know it seems like I’m just trying to get code, but I’d prefer if you gave me the code to do this, i know people don’t like “Spoonfeeding” code, but honestly it’s the best way for me to learn, since whenever I take code, I always like to look at it and understand what does what.

transform.forward

In your case you want to get the forward direction of some camera. So create a Camera variable, drag the camera into that through the inspector, then use cam.transform.forward to get its forward vector, which is the direction the object is pointing in. Multiply it by -1 to get the opposite direction. So for some gameobject “kb” you want to base the knockback direction on (in your case the camera, but may more realistically be the weapon itself as mentioned by others above):

Vector3 kbVec = kb.transform.forward * -1;

On the player object, which has a rigidbody attached to it, you can then apply a force in that direction using AddForce. https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html

So you’d simply write something along those lines:

rb.AddForce(kbVec * kbMultiplier, ForceMode.Impulse);

Where rb is your rigidbody component and kbMultiplier is some value to scale the knockback with.
You may have to implement some way of slowing down after the knockback, but that’s a different story.

A few more general tips. Programming is learning by doing, so looking for and experimenting with solutions is a quite important aspect of improving your understanding. If nothing else you learn how to look for solutions faster. Other than that, there are two very important things you will always need in the future: divide and conquer, and google. If a problem seems to complicated for you to solve, break it down into multiple smaller problems. If these are still too complicated, break them down again. Repeat until you end with tasks you can either complete, or specifically google solutions for. In your case your problem contains two parts. Getting the direction to push your object into, as well as applying a force to an object. Breaking it down like that you have generic easy to lookup questions that should quickly lead you to transform(.forward) aswell as AddForce.
Of course it’s fine to ask questions as well. But learning how to look for answers yourself will speed up the process of learning immensely, so i thought it is worth mentioning how to approach problems in general.

1 Like

I seriously can only answer by quoting myself, because you either can’t read or are blind.

You also sound like you’ve paid $100 to get an answer and are thoroughly disappointed with my lack of servitude and pedagogy. I’m really sorry if my attempt doesn’t help you and I’ll refrain from trying to help you in the future.

No it seems like you don’t actually like to read, and don’t like to learn, and won’t learn, and are pretty ungrateful when other people commit their time and energy. You don’t deserve this. I won’t bother and no one else should. Just my 2c.

I don’t think you understood what I was asking, either, you NEED the CAMERA, to find which way the CAMERA is facing, I want to launch the player the opposite way, the CAMERA, is facing

I’ve already learned quite a lot in unity, and can do a lot on my own, I’ve learned to make minecraft plugins fully on my own by just looking at other peoples’ code, it really DOES help, you just seem overly toxic about me finding your answer unhelpful, honestly, not to be rude, kind of ignorant, how am I supposed to launch the player the oppose what the CAMERA, is looking, without a reference to the CAMERA. I cannot use the weapon, as it rotates somewhat inaccurately, and isn’t always still

Thanks man! it works perfectly & I understand how it works! Thanks a lot

it’s cool man. if you can’t stand my personality, it’s ok. from my point of view, you’re much more toxic, because you’re actively discouraging people who waste their time in order to help you with a mundane issue.

I don’t feel a loss because of the time, I have dedicated that time regardless, but I feel a loss because I could’ve helped someone else instead.

I am coding for a long time, and yes my solutions are sometimes a little bit too complicated for the Average Joe, and if you can’t find my posts useful, and can’t read them properly, to the point of having to underline the same reasoning over and over, even though I’ve addressed it explicitly several times, it’s fine.

I’ll say this just one more time, you don’t need a camera per se, you need a direction in which the player is shooting and you want to introduce a force that is opposite to this direction. that’s all there is to it.

that’s a completely separate thing that normally just coincides with the direction the camera is looking at. but you seem to be far away from any basic understand of how these things work, and furthermore your attitude prevents you from getting better. and when I said it, I was toxic, when someone else said it, you understood everything.

the only reasonable explanation is that you don’t like to read, hate people who make you read, and I don’t want to participate in your desires for instant gratification.

that’s just my opinion.
wish you good luck in any case.
thanks for resolving this misunderstanding in a civilized manner.

I’ll be honest, what you wrote in your first post did kinda overcomplicate the question, but thanks for putting your time to help