Consulting, services, computer engineering. Implementation of technology solutions and support for businesses.

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

Windows 11 v26100 Csharp First FPS Player is shooting bullets

 

Windows 11 v26100 Csharp First FPS Player is shooting bullets

 

Windows 11 v26100 Csharp First FPS Player is shooting bullets

 

 

Who am i / About the author...

ident021 180 facebook linkedin insider mcp learn metadatas sans cravate 128x128 autocolors 18052006 191123 mcse microsoft logomcsa microsoft logomcdba logo

since 2001, Insider since 2014.

 

Thanks to Microsoft EMEA GBS to let me participate in the year 2014 to the Insider project during my work. Then, This Windows test project, here in version 11, is based on the cycle of the insider Preview Builds, now in the Dev Channel: it is fun to test the new features. I can learn new features, validate them and share them with you :-)

Why game engines? Because as a system/network/database developer I only see consoles and screens with unfunny and ugly text. With game engines i can show you colors and animations, that's more fun and more eye-catching :)

This tutorial is made in a test environment, for pleasure and not to earn money. It is a non-profit project. It shows that the concept is possible, for a demontration, artistic, or educational purposes, school learning course. Don't test in a real environment in production. 

 

Windows 11 v26100 Csharp First FPS Player is shooting bullets : last articles

 

 

how to install Godot engine

Windows 11 v23619 testing with a Unity game engine Hello World

How to use signals with Godo Engine (Red bouncing ball)

A Paddle Game with Godot engine

Windows 11 v26058 C Sharp with Copilot Godot Engine multiplayer client server POC

Windows 11 v26080 Blender installation

Windows 11 v26100 Csharp First FPS building the level

Windows 11 v26100 Csharp First FPS creating a health pickup

Windows 11 v26100 Csharp First FPS moving the player

Windows 11 v26100 Csharp First FPS Scripting camera behavior to follow the player

 

 

Windows 11 v26100 Csharp First FPS Player is shooting bullets: the bullet prefab

 

I can use the GameObject.Instantiate() method and provide a Prefab object, a starting position, and a starting rotation.

Hierarchy / I Select + | 3D Object | Sphere

I rename it bullet

Inspector/ I change its Scale to 0.15 in the x, y, and z axes in the Transform component

            Add component : physics/Rigidbody

Projects/Assets/Materials/I create a new material

Rename it Bullet_mat

Albedo : R :255 G :255 B :0

I drag’n drop this material to the Hierarchy /Bullet game object

I create a prefab by drag’n dropping the bullet game object in the prefab folder

Done : the Hierarchy /bullet game object turns to blue because it is now a prefab.

Now, i delete it from the hierarchy

 

Windows 11 v26100 Csharp First FPS Player is shooting bullets: script

 

 

I updated the C# script in the Scripts folder, i name it CameraBehavior

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavior : MonoBehaviour
{

// store the Bullet Prefab
public GameObject Bullet;

//hold the Bullet speed
//public float BulletSpeed = 100f;
public float BulletSpeed = 0f;

// check if our player should be shooting
private bool _isShooting;


// distance we’ll check between the player Capsule Collider and any Ground Layer object
public float DistanceToGround = 0.1f;

// use for the collider detection
public LayerMask GroundLayer;

// store the player’s Capsule Collider component
private CapsuleCollider _col;

public float MoveSpeed = 10f;
public float RotateSpeed = 75f;
private float _vInput;
private float _hInput;

public float JumpVelocity = 5f;
// hold the amount of applied jump force we want
private bool _isJumping;
// check if our player should be jumping

private Rigidbody _rb;
// https://docs.unity3d.com/ScriptReference/Rigidbody.html

void Start()
{

// find and return the Capsule Collider attached to the player
_col = GetComponent<CapsuleCollider>();

_rb = GetComponent<Rigidbody>();
// capture the RigidBody of the scene
}
void Update()
{

// check if our player is supposed to be shooting using the _isShooting variable
_isShooting |= Input.GetKeyDown(KeyCode.Space);

_isJumping |= Input.GetKeyDown(KeyCode.J);
// whether a specified key is pressed during the current frame and will
// only fire once even if J key held down

_vInput = Input.GetAxis("Vertical") * MoveSpeed;
_hInput = Input.GetAxis("Horizontal") * RotateSpeed;
/*
this.transform.Translate(Vector3.forward * _vInput *
Time.deltaTime);
this.transform.Rotate(Vector3.up * _hInput * Time.deltaTime);
*/
}

void FixedUpdate()
{
/* Any physics- or Rigidbody-related code always goes inside the FixedUpdate method,
rather than Update or the other MonoBehavior methods:
• FixedUpdate is frame rate independent and is used for all physics code
*/

if (_isShooting)
{
// assign a GameObject to newBullet by passing in the Bullet Prefab
// new Bullet Prefab in front of the player (one unit forward along the z axis) to avoid any collisions.
GameObject newBullet = Instantiate(Bullet, this.transform.position + new Vector3(0, 0, 1),
this.transform.rotation);

// return and store the Rigidbody component on newBullet
Rigidbody BulletRB = newBullet.GetComponent<Rigidbody>();

// set the velocity property of the Rigidbody component to the player’s transform
BulletRB.velocity = this.transform.forward ;
//* BulletSpeed;

// to false so our shooting input is reset for the next input event.
_isShooting = false;
}

// check whether IsGrounded returns true and the J key is pressed before executing the jump code
if (IsGrounded() && _isJumping)
{
_rb.AddForce(Vector3.up * JumpVelocity, ForceMode.Impulse);
}

Vector3 rotation = Vector3.up * _hInput;
// a new Vector3 variable to store our left and right rotations

Quaternion angleRot = Quaternion.Euler(rotation *
Time.fixedDeltaTime);
// Unity prefers quaternion Euler angles for rotation type
// see https://docs.unity3d.com/Documentation/Manual/QuaternionAndEulerRotationsInUnity.html

_rb.MovePosition(this.transform.position +
this.transform.forward * _vInput * Time.fixedDeltaTime);
/*The vector that’s used can be broken down as follows: the capsule’s Transform
position in the forward direction, multiplied by the vertical inputs and Time.
fixedDeltaTime
*/

_rb.MoveRotation(_rb.rotation * angleRot);
/*
angleRot already has the horizontal inputs from the keyboard, so all we need to
do is multiply the current Rigidbody rotation by angleRot to get the same left
and right rotation
*/

/* if (_isJumping)
{
// pass the Vector3 and ForceMode parameters to RigidBody.AddForce() and make the player jump
_rb.AddForce(Vector3.up * JumpVelocity, ForceMode.Impulse);
// Impulse applies instant force to an object while taking its mass into account
// https://docs.unity3d.com/ScriptReference/ForceMode.html
}
*/

_isJumping = false;
// reset _isJumping to false so the input check knows a complete jump and the landing cycle have been completed

}

// method with a bool return type.
private bool IsGrounded()
{
// store the position at the bottom of the player’s Cap-sule Collider
Vector3 capsuleBottom = new Vector3(_col.bounds.center.x,
_col.bounds.min.y, _col.bounds.center.z);

// store the result of the CheckCapsule()
bool grounded = Physics.CheckCapsule(_col.bounds.center,
capsuleBottom, DistanceToGround, GroundLayer,
QueryTriggerInteraction.Ignore);

// return if the player is on the ground
return grounded;

}

}

 

Good practise is to make sure that unused objects are regularly deleted to avoid overloading the program.

destroy each bullet after a set delay time : ensure that the bullet disapear after an amount of time.

I create a new C# script in the Scripts folder and I rename it BulletBehavior

I drag and drop the BulletBehavior script onto the Bullet Prefab in the Prefabs folder

Or Assets/Prefabs/Bullet/Add component/Scripts/BulletBehavior

Here is the code :

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletBehavior : MonoBehaviour
{
// store how long we want the Bullet Prefabs to remain in the scene after they are instantiated
public float OnscreenDelay = 3f;

void Start ()
{
// Destroy() can optionally take an additional float parameter as a delay, which we use to keep the bullets on screen for a short amount of time
Destroy(this.gameObject, OnscreenDelay);
}
}

 

When i test with play of F5, when i press SPACE, the player shots the bullets, and the bullets disappears from the Hierarchy after a short period of time ! Great !

 

 

It is a Component Design Pattern of Unity.

 

 

Windows 11 v26100 Csharp First FPS Player is shooting bullets : conclusion done

 

Done! i created the project Csharp First FPS Player is shooting bullets, on windows 11 version 26100.

Windows 11 v26100 Csharp First FPS Player is shooting bullets

Windows 11 v26100 Csharp First FPS Player shooting bullets : need help ? 

Need help with Windows 11 or C# with Unity?

Fill this form or send an email on loic @consultingit.fr or This email address is being protected from spambots. You need JavaScript enabled to view it. and i will be happy to help you :)

 

 

 

When i test with play of F5, when i press SPACE, the player shots the bullets, and the bullets disappears from the Hierarchy after a short period of time ! Great !

 

It is a Component Design Pattern of Unity.