Bullet Prefab fire in the same direction the player is facing - c#

So I am trying to have my bullet prefab fire in the same direction that my player is facing. Currently if the player faces north that's where the bullet fires, if the player faces south the bullet still fires north shooting straight through the player backwards.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireRocket : MonoBehaviour
{
public GameObject rocketPrefab;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject rocketObject = Instantiate(rocketPrefab);
rocketObject.transform.position = this.transform.position + transform.forward;
}
}
}
The bullet has a box collider and a rigidbody with the script attached. What else do i need to include so that I can have my bullet fire in the same direction my player is facing?
Rocket Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket: MonoBehaviour
{
public float speed = 15f;
public float RocketLife = 10f;
private float RocketLifeTimer;
// Start is called before the first frame update
void Start()
{
RocketLifeTimer = RocketLife;
}
// Update is called once per frame
void Update()
{
transform.position += transform.forward * speed * Time.deltaTime;
RocketLife -= Time.deltaTime;
if (RocketLifeTimer <= 0f)
{
Destroy(this.gameObject);
}
}
}

you need to add transform.rotation = player rotation / or camera rotation

Related

Why does my Player in Unity fall down when I start PlayMode?

Video explanation
My cube in Unity is falling down randomly.It is on a cube named "Ground" and it has a movement script attached below. Above is the video showing what happens, and I'll attach an image too. Image
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 6f;
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
controller.Move(direction * speed * Time.deltaTime);
}
}
}
Make sure the colider covers the entire cube, because now it’s only of size 1 on all axis.

Projectiles not killing player ship?

I added this script to the enemy ship and tried using it on the player ship but the projectiles still do not shoot and kill the player ship. I trying to get the laser guns on the enemy ship to kill the player ship. But my script is not working. in the inspector in Unity, I needed to add the player ship to public Rigidbody projectile; so I did when trying to add the script to either or the enemy ship or player ship the enemy laser bullets still don't kill the player ship. But the enemy ship and its bullets follow the player ship though so that works. Any insight is welcomed :/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectiles : MonoBehaviour
{
public Transform playerShip;
public float range = 20.0f;
public float enemyGunImpulse = 10.0f;
bool onRange = false;
public Rigidbody projectile;
void Start()
{
float rand = Random.Range(1.0f, 2.0f);
InvokeRepeating("Shoot", 2, rand);
}
void Shoot()
{
if (onRange)
{
Rigidbody enemyGun = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
enemyGun.AddForce(transform.forward * enemyGunImpulse, ForceMode.Impulse);
Destroy(enemyGun.gameObject, 2);
}
}
void Update()
{
onRange = Vector3.Distance(transform.position, playerShip.position) < range;
if (onRange)
transform.LookAt(playerShip);
}
}

why when using navmeshagent when clicking with the mouse the player is going to a point and keep moving there?

I have a FPSController attached to it: a RigidBody , Animator , NavMeshAgentand two scripts: PlayerController and AgentController.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
float translatioin = Input.GetAxis("Vertical") * speed;
float straffe = Input.GetAxis("Horizontal") * speed;
translatioin *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translatioin);
if (Input.GetKeyDown("escape"))
Cursor.lockState = CursorLockMode.None;
}
}
And
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AgentController : MonoBehaviour
{
public Camera camera;
public NavMeshAgent agent;
public bool agentControl = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0) && agentControl == true)
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
agent.SetDestination(hit.point);
}
}
}
}
With the PlayerController I can move around using the keys WSAD and with the AgentController I can click on some point on the terrain and the Agent will walk over there.
When I click for example on one of the big cubes the player is walks over it and stop near it. But then when I'm using the keys WSAD to move back away from the cube the player will keep moving automaticaly back to the cube.
Like a magnet that make the player keep moving to the cube to the same point I clicked on before.
On the FPSCamera I have a script: Just to use the mouse look around.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camMouseLook : MonoBehaviour
{
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
GameObject character;
// Use this for initialization
void Start ()
{
character = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update ()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
mouseLook.y = Mathf.Clamp(mouseLook.y, -90f, 90f);
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, Vector3.up);
}
}
I found that while the game is running if I uncheck the NavMeshAgent then I will be able to walk around again fine with the keys but when the NavMeshAgent is on and I click on some cube it will keep moving to that cube even if I'm moving with the keys to other places.
I want to be able either using the AgentController and/or the PlayerControllerwhen the game is running.
UPDATE:
I tried to use OnCollisionEnter and OnCollisionExit
But once I set the move to false again on the OnCollisionExit I'm getting the same problem. The reason is that I set the move to true again in the OnCollisionExit is to be able to click the mouse and move again.
So I'm stuck again.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AgentController : MonoBehaviour
{
public Camera camera;
public NavMeshAgent agent;
public bool move = true;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0) && move == true)
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
agent.SetDestination(hit.point);
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "HitPoint")
{
move = false;
}
}
private void OnCollisionExit(Collision collision)
{
move = true;
}
}
This probably happened because you're setting the destination to positions inside the cubes, so your agent keeps trying to reach them though it's impossible.
First of all, you may want to tell your agent to stop once one of the movement keys is pressed to avoid conflicts. You can use this to stop:
agent.isStopped = true;
agent.velocity = Vector3.zero;
If this is not enought to solve the problem, one workaround would be to put a Nav Mesh Obstacle Component in your cubes, check Carve and rebake your Nav Mesh. This way the agent would stop in the nearest point from the one you set, outside the cube.
A second option would be to check the collision with the cubes, and tell your agent to stop once it collides with the one you clicked.
Hopefully one of these will work for you!

Bullet does not move forward when spacebar is pressed (Unity 2D)

I'm replicating project from this site below:
http://blog.lessmilk.com/unity-spaceshooter-1/
http://blog.lessmilk.com/unity-spaceshooter-2/
But, my bullet does not move forward when the spacebar is pressed. Below are my scripts:
spaceshipScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spaceshipScript : MonoBehaviour {
public GameObject bullet;
// Use this for initialization
void Start () {
}
void Update() {
// Get the rigidbody component
//var r2d = GetComponent("Rigidbody2D");
float speed = 10.0f;
// Move the spaceship when an arrow key is pressed
if (Input.GetKey (KeyCode.RightArrow))
transform.position += Vector3.right * speed * Time.deltaTime;
else if (Input.GetKey (KeyCode.LeftArrow))
transform.position += Vector3.left * speed * Time.deltaTime;
//BULLET
//When spacebar is pressed
if (Input.GetKeyDown(KeyCode.Space)) {
Instantiate(bullet, transform.position, Quaternion.identity);
}
}
}
bulletScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bulletScript : MonoBehaviour {
public int speed = 8;
// Use this for initialization
void Start () {
Input.GetKey (KeyCode.UpArrow);
transform.position += Vector3.right * speed * Time.deltaTime;
}
void OnBecomeInvisible() {
Destroy (gameObject);
}
// Update is called once per frame
void Update () {
}
}
As they are telling you in the comments, you are mixing two different approaches. If you want to modify the position of the bullet using Time.deltaTime you need to move that line to Update()
However if you want to follow the approach of the tutorial, but instead of shooting the bullet from bottom to top, you want to shoot from left to right, you should just change the axis (And dont forget to add a rigid body to the bullet)
// Public variable
public var speed : int = 6;
// Function called once when the bullet is created
function Start () {
// Get the rigidbody component
var r2d = GetComponent("Rigidbody2D");
// Make the bullet move upward
r2d.velocity.x = speed;
}
// Function called when the object goes out of the screen
function OnBecameInvisible() {
// Destroy the bullet
Destroy(gameObject);
}

How to prevent player from shooting projectiles after ammo depletion

I'm making a game that is similar to Space Shooter, and I would like to know how to prevent a player from shooting projectiles AFTER the ammo has depleted.
The two scripts below controls my player's movement and actions, and decreases the current projectile count each time the player hits spacebar.
Player script
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
//Movement speed of Player sprite
public float Speed = 20.5f;
//GameObject to store the projectile object
public GameObject Projectile;
// Update is called once per frame
void Update ()
{
//If left arrow key is pressed
if (Input.GetKey (KeyCode.LeftArrow))
//Move the player to the left
transform.Translate (new Vector2 (-Speed * Time.deltaTime, 0f));
//If right arrow key is pressed
if (Input.GetKey (KeyCode.RightArrow))
//Move the player to the right
transform.Translate (new Vector2 (Speed * Time.deltaTime, 0f));
//If the spacebar is pressed
if (Input.GetKeyDown (KeyCode.Space))
{
//Instatiate a new projectile prefab 2 units above the Player sprite
Instantiate (Projectile, transform.position + transform.up * 2, Quaternion.identity);
//Find the game object with the tag "Projectile" and call the DecreaseProjectileCount() function from the ProjectileTracker script
GameObject.FindGameObjectWithTag("Projectile").GetComponent<ProjectileTracker>().DecreaseProjectileCount();
}
}
}
ProjectileTracker script
using UnityEngine;
using System.Collections;
public class ProjectileTracker : MonoBehaviour {
//Variable to store the current projectile count
public GameObject ProjectileRef;
//Set the current projectile count to be 8
int CurrentProjectileCount = 8;
//Function to decrease the current projectile count
public void DecreaseProjectileCount()
{
//Decrease the current projectile count by 1
CurrentProjectileCount--;
//Print out the current projectile count
ProjectileRef.GetComponent<TextMesh> ().text = CurrentProjecileCount.ToString ();
}
}
Any form of help is appreciated!
The way i would personally do it:
ProjectileTracker tracker = GameObject.FindGameObjectWithTag("Projectile").GetComponent<ProjectileTracker>();
//If the spacebar is pressed
if (Input.GetKeyDown (KeyCode.Space) && tracker.ProjectileCount > 0)
{
//Instatiate a new projectile prefab 2 units above the Player sprite
Instantiate (Projectile, transform.position + transform.up * 2, Quaternion.identity);
//Find the game object with the tag "Projectile" and call the DecreaseProjectileCount() function from the ProjectileTracker script
tracker.ProjectileCount--;
}
...
using UnityEngine;
using System.Collections;
public class ProjectileTracker : MonoBehaviour {
//Variable to store the current projectile count
public GameObject ProjectileRef;
//Set the current projectile count to be 8
private int projectileCount = 8;
public int ProjectileCount
{
get { return projectileCount; }
set { SetProjectileCount(value); }
}
//Function to decrease the current projectile count
public void SetProjectileCount(int value)
{
projectileCount = value;
//Print out the current projectile count
ProjectileRef.GetComponent<TextMesh> ().text = value.ToString();
}
}

Categories

Resources