Gun shoots even if gun isnt picked up Unity 3D - c#

My gun code is linked to the gun itself, however even when I'm not holding the gun (aka it's not picked up yet) the gun still shoots and fires at where I'm looking, I will give the code and I'm thinking of something like 'if is child then shoot'.
Here is the code in question, if you need the full code I'd be happy to oblige.
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float Impact = 40f;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
private float nextTimeToFire = 0f;
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
void Shoot()
{

public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float Impact = 40f;
public Camera fpsCam;
public bool pickedUp = false;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
private float nextTimeToFire = 0f;
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire && pickedUp)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
When the gun is picked up, set the pickedUp boolean to true and false when it is dropped.

public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float Impact = 40f;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
private float nextTimeToFire = 0f;
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire && parent != null)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}

Related

How I can move player left or right with infinite runner game here. using character controller

public class PlayerMove : MonoBehaviour
{
public float speed;
private float yVelocity;
public CharacterController player;
public float jumpHeight =10.0f;
public float gravity = 1.0f;
//public float gravityScale = 1;
private void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
Vector3 direction= new Vector3(0, 0, 1);
Vector3 velocity= direction * speed;
if (player.isGrounded == true)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpHeight;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
player.Move(velocity * Time.deltaTime);
}
}
I tried Rigidbody & much more script but my player doesn't jump if my player jump then my doesn't move left or right sometimes my player stocked in ground.. tell me the right way of script where I can use
For the left/right movements you can try this simple code :
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float speed;
private float yVelocity;
public CharacterController player;
public float jumpForce = 10.0f;
public float moveForce = 5.0f;
public float gravity = 1.0f;
private void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
Vector3 direction = new Vector3(0, 0, 1);
Vector3 velocity = direction * speed;
// Add left/right movement
if (Input.GetKey(KeyCode.LeftArrow))
{
velocity += Vector3.left * moveForce;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
velocity += Vector3.right * moveForce;
}
if (player.isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpForce;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
player.Move(velocity * Time.deltaTime);
}
}
You can also look at this post Moving player in Subway Surf like game using left/right swipe

Bullet Impact force not working as intended

When I shoot my bullet on a rigid body, it just moves in the wrong direction (to the right, when it is supposed to go forward) Here is the script that handle bullet and target interactions.
I have no idea why this isn't working and help would be appreciated.
thx
using UnityEngine;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float impactForce = 200f;
public ParticleSystem muzzleFlash;
private float nextTimeToFire = 0f;
public Camera fpsCam;
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
void Shoot()
{
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
hit.rigidbody.AddForceAtPosition(transform.forward * impactForce, hit.point);
}
}
}
}
You're using the wrong transform to get the forward vector from.
if (target != null)
{
target.TakeDamage(damage);
hit.rigidbody.AddForceAtPosition(transform.forward * impactForce, hit.point);
}
should be:
if (target != null)
{
target.TakeDamage(damage);
hit.rigidbody.AddForceAtPosition(fpsCam.transform.forward * impactForce, hit.point);
}

Xbox one controller spinning player in unity 3d

I am making an fps game and I want to map my Xbox one controller so that I can use it in my game. All of the buttons and the left joystick work. But, when I try to map the right joystick and play the game my camera looks up and my player starts spinning around. Here is the code for my camera: `
public string mouseXinputname, mouseYinputname;
public float mouseSensitivity;
private float Xaxisclamp;
[SerializeField] private Transform playerBody;
private void Awake()
{
LockCursor();
Xaxisclamp = 0.00f;
}
private void LockCursor ()
{
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
CameraRotaion();
}
private void CameraRotaion ()
{
float mouseX = Input.GetAxis(mouseXinputname) * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis(mouseYinputname) * mouseSensitivity * Time.deltaTime;
transform.Rotate(Vector3.left * mouseY);
playerBody.Rotate(Vector3.up * mouseX);
Xaxisclamp += mouseY;
if(Xaxisclamp > 90.0f)
{
Xaxisclamp = 90.0f;
mouseY = 0.0f;
ClampXaxisRotationToValue(270.0f);
}
else if (Xaxisclamp < -90.0f)
{
Xaxisclamp = -90.0f;
mouseY = 0.0f;
ClampXaxisRotationToValue(90.0f);
}
}
private void ClampXaxisRotationToValue(float value)
{
Vector3 eulerRotation = transform.eulerAngles;
eulerRotation.x = value;
transform.eulerAngles = eulerRotation;
}`
And here is the code for my player controller:
public CharacterController character;
public float speed = 10f;
Vector3 velocity;
public float gravtiy = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;
public float jumpHeight = 3f;
public float sprint = 20f;
public float crouchHeight = 1.0f;
public float crouchSpeed = 5f;
private void Start()
{
character.GetComponent<CharacterController>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0 )
{
velocity.y = -2.0f;
}
if (Input.GetButtonDown("Sprint"))
{
speed = sprint;
}
if (Input.GetButtonUp("Sprint"))
{
speed = 10f;
}
if (Input.GetButtonDown("Crouch"))
{
character.height = crouchHeight;
speed = crouchSpeed;
}
if (Input.GetButtonUp("Crouch"))
{
character.height = 2f;
speed = 10f;
}
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
Vector3 move = transform.right * hor + transform.forward * ver;
character.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravtiy);
}
velocity.y += gravtiy * Time.deltaTime;
character.Move(velocity * Time.deltaTime);
I included all of my code so you can copy and paste it into your own unity project so you can see what I mean.
BTW: The inputs "Crouch" and "Sprint" are custom inputs and you'll have to create them in Project Settings > Input Manager

How do I lock the camera horizontal rotation if speed is 0 or less?

I'm working on a cars game and I'm trying to prevent the camera from moving horizontally if the model speed is null, I have tried many things, however I seem unable to do this because either when I get the camera to get locked it remains locked even if the object moves, and if not that it just keeps moving even with the object stopped, so I want to know how can I make that happen.
Code for cam Class
public class Cam : MonoBehaviour
{
public float sensitivityHor = 9.0f;
public float sensitivityVert = 9.0f;
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
public enum rotationAxes
{
//Given aliases to X and Y cordinates
keyX = 1,
}
public rotationAxes axes = rotationAxes.keyX;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Movement mov = GetComponent<Movement>();
if (mov.speed > mov.speed && mov.speed > 0 && axes == rotationAxes.keyX)
{
//Movimiento en el eje X de la camara
transform.Rotate(0, Input.GetAxis("Horizontal") * sensitivityHor, 0);
}
}
}
code for Movement class
public class Movement : MonoBehaviour
{
private CharacterController _charController;
public float speed = 3.0f;
// Start is called before the first frame update
void Start()
{
_charController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
float deltaZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(0, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed);
movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);
_charController.Move(movement);
}
}
You never change the value of speed so what sense does it make to check it?
Rather store the actual speed you are going to apply to the object in this frame
public class Movement : MonoBehaviour
{
[Header("References")]
[SerializeField] private CharacterController _charController;
[Header("Settings")]
[SerializeField] private float speed = 3.0f;
[Header("Debug")]
[SerializeField] private float actualSpeed;
// public Read-only property
public float ActualSpeed => actualSpeed;
// Start is called before the first frame update
private void Awake()
{
if(!_charController) _charController = GetComponent<CharacterController>();
}
// Update is called once per frame
private void Update()
{
actualSpeed = Input.GetAxis("Vertical") * speed;
// It is cheaper to clamp a single float value then a vector
// since "GetAxis" retusn a value between -1 and 1
// it will anyway never be greater then "speed" so enough
// to clamp it downwards
actualSpeed = Mathf.Max(deltaZ, 0);
actualSpeed *= Time.deltaTime;
// This already uses the world space forward vector
_charController.Move(transfor.forward * actualSpeed);
}
}
And now you can rather check for this actualSpeed value
[RequireComponent(typeof(Movement))]
public class Cam : MonoBehaviour
{
[Header("References")]
// Better reference this already via the Inspector
[SerializeField] private Movement mov;
[Header("Settings")]
[SerializeField] private float sensitivityHor = 9.0f;
[SerializeField] private float sensitivityVert = 9.0f;
[SerializeField] private float minimumVert = -45.0f;
[SerializeField] private float maximumVert = 45.0f;
[Space]
[SerializeField] private rotationAxes axes = rotationAxes.keyX;
public enum rotationAxes
{
//Given aliases to X and Y cordinates
keyX = 1,
}
private void Awake()
{
// as fallback get it ONCE
if(!mov) mov = GetComponent<Movement>();
}
// Update is called once per frame
private void Update()
{
if (mov.ActualSpeed > 0 && axes == rotationAxes.keyX)
{
transform.Rotate(0, Input.GetAxis("Horizontal") * sensitivityHor, 0);
}
}
}

Enemies movement is not smooth

When my enemies move, they move from one position to the next without moving in between the points. I want the enemies to move between two positions smoothly, and I do not understand why the enemies do not do so with the following code.
public class UltPatrol : MonoBehaviour
{
public float speed;
public Transform Enemypos;
private float waitTime;
public float StartwaitTime;
public float MinX;
public float MaxX;
public float MinY;
public float MaxY;
private void Start()
{
Enemypos = GetComponentInParent<Transform>();
waitTime = StartwaitTime;
Enemypos.localPosition = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxY));
}
private void Update()
{
transform.localPosition = Vector2.MoveTowards(transform.localPosition, Enemypos.localPosition, speed * Time.deltaTime);
if (Vector2.Distance(transform.localPosition, Enemypos.localPosition) <0.2f)
{
if (waitTime <= 0)
{
Enemypos.localPosition = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxY));
waitTime = StartwaitTime;
}
else
{
waitTime -= Time.deltaTime;
}
}
}
}
Are you trying to get your game to look like this
All I did was remove the line
Enemypos = GetComponentInParent<Transform>();
And then in the editor, I un-parented the two objects, and assigned the value of Enemypos in the inspector.

Categories