How to do i add a sudden burst of force to a object in the direction the player is facing?

Updated on May 31, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on May 30, 2018

I am working on a shooting mechanic for my game. I currently have it so when space is pressed it spawns a object and adds force to it. The thing is this force is set to go on the z axis and not where the player is facing. I have the bullet spawn where the player is facing though. also this force keeps getting exerted the as long as you hold down space.

If anyone knows how to better make this script please help.

Script that i want to add force relative to where the player is looking. and force that only gets applied to it right after it spawns.

using UnityEngine;

public class Speed : MonoBehaviour {

public Rigidbody rbo;
public float ms = 50f;

void Update () {

if (Input.GetKey(“space”))
{
rbo.AddForce(ms* Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
}

Script that spawns the bullet

using UnityEngine;

public class shooting : MonoBehaviour
{
public GameObject prefab;
float distance = 1.0f;

float nextSpawnTime;
float spawndelay = 1;

bool ShouldSpawn()
{
return Time.time >= nextSpawnTime;
}

void Update()
{
if (ShouldSpawn())
{
Spawn();
}
}
void Spawn()
{
if (Input.GetKey(“space”))
{
nextSpawnTime = Time.time + spawndelay;
Instantiate(prefab, transform.position + transform.forward * distance, transform.rotation);
}

}
}

  • Liked by
Reply
0 on May 30, 2018

You can get the direction player is looking from either the player object itself, or if the game is first person through the camera with:

Vector3 direction = Camera.main.transform.forward;

 

to add force, you just need to grab the Rigidbody from the prefab when you spawn it, and add the force then and there.

Instantiate(prefab, transform.position + transform.forward * distance, transform.rotation).GetComponent<Rigidbody>().AddForce(direction * strength);
  • Liked by
Reply
Cancel
0 on May 31, 2018

ok thanks I found a solution to fix it

  • Liked by
Reply
Cancel