Showing posts with label particles. Show all posts
Showing posts with label particles. Show all posts

Saturday, September 23, 2023

91.) Mastering First-Person Camera Controls: Preventing Y-Angle Flipping in Your Game

   

     In the world of game development, creating an immersive first-person experience is a key goal for many developers. One of the fundamental aspects of achieving this goal is getting your camera controls just right. However, a common issue that plagues many first-person games is the Y-angle flipping problem. Character movement and camera control are critical aspects of creating an immersive gaming experience. In this blog post, we'll discuss a common issue in character movement using XNA (Microsoft XNA Community Game Platform): preventing the character's head from flipping or rotating too far on the vertical (Y) axis. We'll provide you with a step-by-step guide on how to restrict the vertical rotation of your character's head to keep it within a specified range. Lets dive into this issue and show you how to prevent it in your game. We will test this first with the original XNA 4.0 Basic FPS Kit inspired by Starship Troopers for you to experiment and try yourself and then another example based on the XNA Chase Camera Sample.


How to Prevent the Y-Angle from Flipping with the XNA 4.0 Basic FPS Kit 



The Y-Angle Flipping Problem

     Before we dive into the solution, let's understand the problem. In many first-person games, the camera is controlled by the player's mouse movements. When a player looks up or down, the Y-angle of the camera changes. However, without proper handling, this can lead to a frustrating experience where the camera flips upside down when the player looks too far up or down.

     Imagine you have a character in your game, and you want players to control the character's viewpoint. However, you don't want the character's head to flip or rotate upside down, as it can break the immersion and create an unrealistic experience for players.


The Solution: Clamping the Y-Angle

     The solution to preventing Y-angle flipping is to clamp the Y-angle within a certain range. This ensures that the camera can't rotate too far up or down, keeping the player's perspective consistent and avoiding the dreaded flip.


Here's a step-by-step guide to implementing this solution in the fps kit:

1. Track Mouse Movements

First, you'll want to track the player's mouse movements. Most game development libraries provide functions to get the mouse's current position.


MouseState mouse = Mouse.GetState();

float deltaX = (mouse.X - centerX) * TurnSpeed * 0.01f;

float deltaY = (mouse.Y - centerY) * TurnSpeed * 0.01f;


2. Update Y-Angle

Update the Y-angle (horizontal rotation) of your camera based on the horizontal mouse movement.

Angle.Y += MathHelper.ToRadians(deltaX);


3. Clamp the X-Angle

Now comes the critical part. You'll want to clamp the X-angle (vertical rotation) to prevent it from going too far up or down. Use MathHelper.Clamp to restrict the angle within a reasonable range.

Angle.X = MathHelper.Clamp(Angle.X + MathHelper.ToRadians(deltaY), -MathHelper.PiOver2, MathHelper.PiOver2);

With this clamping in place, your camera will never flip upside down, no matter how far the player looks up or down.


4. Implement Camera Movement

     Of course, camera controls involve more than just looking around. You'll also want to implement movement controls, such as forward, backward, strafing left, and strafing right. The specifics of this will depend on your game engine and architecture, but ensure that these movements take the camera's orientation into account.


5. Apply the Camera Transformation

Finally, don't forget to update the camera's view matrix or equivalent transformation based on the camera's position and orientation. This matrix is crucial for rendering the game world correctly from the player's perspective. The source code with the solution provided above is available to download below.





 
First-Person Camera Flip Prevention Example 2
     We'll show you how to solve this problem using another example based off the Chase Camera Sample.

Step 1: Define a Maximum Rotation Limit

To prevent the character's head from flipping too far, you need to define a maximum rotation limit. This limit determines the maximum angle (in radians) your character's head can rotate on the vertical (Y) axis. You can adjust this limit based on your game's requirements. Here's how to define it:

float maxYRotation = MathHelper.ToRadians(80); // Set the maximum allowed Y rotation in radians (adjust as needed)

In this example, we've set maxYRotation to 80 degrees. Feel free to change this value to match your desired rotation limit.


Step 2: Clamp the Rotation Amount

Next, you need to ensure that the rotation amount (rotationAmount.Y) stays within the specified range. To do this, use the MathHelper.Clamp function:

rotationAmount.Y = MathHelper.Clamp(rotationAmount.Y, -maxYRotation, maxYRotation);

This line of code restricts the vertical rotation (rotationAmount.Y) to stay within the range of -maxYRotation (negative limit) and maxYRotation (positive limit).


Step 3: Create the Rotation Matrix

With the rotation amount clamped to the specified range, you can create a rotation matrix that represents the character's head orientation. This matrix ensures that the character's head remains within the allowed rotation limits:

rotationMatrix =

    Matrix.CreateFromAxisAngle(Right, rotationAmount.Y) *

    Matrix.CreateRotationY(rotationAmount.X);


     This code creates the rotation matrix using both the vertical (Y-axis) and horizontal (X-axis) rotation amounts. The Right vector is used to determine the axis of rotation. By following these three simple steps, you can prevent your character's head from flipping or rotating too far on the vertical axis in XNA. This not only enhances the realism of your game but also ensures a smoother and more immersive gaming experience for your players. Remember to adjust the maxYRotation value to suit your game's specific needs. With this control in place, you can create more enjoyable and realistic character movement and camera control in your XNA games.


Conclusion

     In the world of game development, smooth and intuitive first-person camera controls are essential for creating an immersive experience. By understanding and addressing the Y-angle flipping problem, you can provide players with a more enjoyable and frustration-free gaming experience.

     Implementing these solutions will go a long way in improving your game's camera controls, making it more enjoyable and engaging for players. So, go ahead and give it a try in your next game project, and watch as your players appreciate the smoother, more immersive experience you've created. Happy coding!

Wednesday, February 15, 2023

86.) Ai Obstacle Avoidance & A-Star Pathfinding Behaviors


      Originally created by David Ang, this demo showcases a tower defense game where entities (spiders and marines) try to reach a destination (blue fiery portal) while avoiding obstacles using either steering behavior (spiders) or A* (marines) pathfinding. Tanks have been added as towers that rotate to face the furthest entity within its range. Particle effects are utilized to show starting points and destination points. This demo outlines the code for the entities avoiding obstacles with a bounding sphere and finding a path using A*. This 3D sample also implements particle systems defined by XML files loaded with the Content Pipeline. David's original demo was created in XNA 3.1. I have successfully updated the source code to XNA 4.0 and made additional implementations. The sample originally utilized the Skinned Model Library but I've replaced it with an updated version of the XNAnimation Library. Doing so allowed me to resolve animation take issues within the spider model and support multiple animation clips within the same .fbx model file. 



     I look forward to expanding this inside the Cyclone Game Engine. Soon I plan to add additional particle effects and possibly a level editor. I have provided the source code to this demo below. 








Monday, February 20, 2017

45. Blood Splatter Test in Starship Troopers?



       This is based off the starter-kit by Hardworker Game Studios which is outdated. I have updated it and re-programmed it in my game engine built upon the XNA 4.0 and MonoGame Fraweworks with the added blood-splatter. It runs on Windows 7, 8 and 10. This program also can run on other platforms supported by MonoGame. The models are simply just a placeholder. This is the beginnings of the AI which is set to simply wander for now.


How do Bullets Work in Games?

Hitscan
       Like the earlier days, the bullets are rendered through a technique called ray-casting. Ray-casting allows the engine to determine the first object intersected by a ray. The majority of games just cast rays along the bullet trajectory to see if there is any collision. This works well since the size of the bullet is usually tiny compared to the size of the world. Many games program bullet sprites (2D images) rendered in 3D which are cast along the ray to provide a visual to the player of bullet projectiles being fired. This also helps with performance. So most cases, game developers find physically modelling a bullet usually pointless. Bounding spheres are attached to the bones of the enemy models for hit detection. So when the ray intersects the bounding spheres, the blood particle effect is emitted. To learn more about implementing ray-casts in your own game projects, check out the Triangle Picking Sample.

       Popular games that use hitscan are Wolfenstein 3D, Doom, Overwatch, Halo and Call of Duty. One of the biggest disadvantages of ray-casting is that the rays have an infinite traveling velocity. Regardless of the range, the rays reach their destination instantly. This ultimately means there is no travel time after you fire a bullet and hit an object. This is not the best method depending on the type of gun used in a game that's based on realism because if the enemy target is miles away, it's impossible to dodge a bullet. In other words, a pistol would have the shooting range of a sniper. Most implementations of hitscans use straight rays. This makes it hard to take into account wind, gravity and other external factors that may affect the bullet once it leaves the gun. So once a player fires their gun, there is no real way to modify its path in the middle. For a "casual" gamers like myself, the hitscan method is a simple learning curve especially for beginner players. However, for games that aim to create an "immersive realistic" shooting experience, the hitscan method creates constraints for their players. This brings me to the next popular method. 


Projectile Ballistics 
       Soon, I plan to run some tests to where the bullets are actual 3D models that will intersect the bounding spheres of the enemies. Why you might ask? In one of my long-term game projects, the modelling of gravity, wind and resistance on the bullet is important as well as seeing bullets being deflected in real-time. With projectile ballistics, every bullet or projectile shot our of a weapon creates a new physics object in the environment. It has its own mass, velocity and hitbox that the game engine will track. This is a priority in games where realism is praised. The drawback to projectile ballistics is that there are additional computations and more processing required in comparison to the hitscan method which is less taxing. Also, game servers will have to make a greater effort making sure all the objects are in sync and remove any conflicts across clients to create smooth multi-player online experiences. 

      Popular games that utilize projectile ballistics are Max Payne and Sniper Elite. Max Payne is known for their popular "Bullet-time" system. Projectile Ballistics is also handy for travel time when taking a long-distance shot or delayed explosions for grenades. For now, I am using the hitscan method. I have also added audio for the gun-fire. Later I plan to add my physics engine and the animated mutant spider beast models. I did not add my physics engine just yet because the terrain was outdated and I didn't want the player as well as the enemies falling infinitely. Once my physics engine is added, the hit detection will be far more accurate. Hopefully I will have the real-time fur effect implemented on the animated spider beast model soon.


Hybrid Systems 
       Many game engines today utilize both hitscan and projectile ballistics. This allows their games to implement a huge variety of weapons. Games such as Halo and Half-Life have weapons that support both these types of physics systems. In Halo, the popular Assault Rifle uses the hitscan method and the Needler uses projectile ballistics. What I've always found unique about the Needler and heat-seeking missiles in flight games is their tracking abilities. The Needler only tracks when the reticule is red which is also true for some flight based games when they lock onto their targets within range. Whenever you're in combat against the Needler, it is smart to go behind cover to block the needles. If you have a long range weapon, or just want to avoid the Needler completely, then be sure to keep your distance away from the enemy using the Needler.















Source Code:



What's All Included: 
1.Basic Rendering system with basic effect.
2. Particle System.
3. Basic object management.
4. The XNA Terrain Library is outdated so I will add my own terrain from my game engine later
5. The XNA 4.0 Skinned Model Sample Pipeline (The Cyclone Game Engine's XNAnimation Library will be used instead in the future to replace this)
6. Anti aliasing 4X
7. Gun-Fire Sound Effect


Saturday, May 14, 2016

36. XNA 4.0 Parallax Occlusion Mapping

     

       Recently, I came across Electronic Meteor's blog post which updated the Parallax Occlusion Mapping Sample to XNA 4.0. In short, parallax mapping is a way to make textures pop out. It's a very efficient way to add depth to a texture, so there is no tessellation here. Parallax Occlusion Mapping was utilized in the hit first-person shooter game called Crysis. This sample also demonstrates another technique called Normal Mapping. In this sample you can switch between the techniques to see each of their effects. The sample was originally created by Alex Alvarex Urban and updated to XNA 3.1 by Canton Javier Ferrero. Thanks to Chris, the sample was updated to XNA 4.0, however he ran into some problems getting the particle system to work. In time, I was able to fix it. I have made the source code available at the following link below for download. If you have found this sample helpful or run into any problems, please comment below.

Also, on a side note, make sure under the File Properties for the smoke.png image, click the drop-down arrow under Content Processor and set the following values like so if they aren't already:

• Color Key Enabled = True
• Generate Mipmaps = True
• Premultiplay Alpha = False
• Resize to Power of Two = False
• Texture Format = DxtCompressed


Download


Friday, March 4, 2016

30. XNA Vehicle Physics Test 4


       In this update, I am continuing to modify and expand the JigLibX (Jiggle Library X) Physics Engine. Recently I added an exhaust particle effect to the vehicle. You can download the XNA 4.0  version of JigLibX below.



       This particle effect streams behind the vehicle when the player presses the gas so often. I will change the color of the smoke to grey. The standard vehicle class in my game engine has a hand brake that locks the rear wheels, thereby creating some drag and slowing the car down. That part is realistic. What isn't realistic is the rear wheels still have full traction. If you've ever pulled a hand brake in a car while moving you've notice that the rear end loses traction and wants to swing around causing a spin. It can be useful for making tight 180 degree turns, orienting your car coming into a turn and for good 'ol fashioned fun. This is why I kept this feature. 


Adding the smoke particle

Vector3 OffsetAmount = new Vector3(0, 0, -3);

Vector3 OffsetPosition = Car.carObject.Car.Chassis.Body.Position +
    (Car.carObject.Car.Chassis.Body.Orientation.Right * OffsetAmount.Z) +
    (Car.carObject.Car.Chassis.Body.Orientation.Up * OffsetAmount.Y) -
    (Car.carObject.Car.Chassis.Body.Orientation.Forward * OffsetAmount.X);


ParticleComponent.smokeParticles.AddParticle(OffsetPosition, Vector3.Zero);


       OffsetAmount is a Vector3 that is the relative offset you want, in this case 3 units behind the center of the car. OffsetPosition is the final, global, relative position, that you can then pass into your particle system or something. It took some trial and error to get all of these working correctly, but I've tested it in several positions and it seems to work OK. And the last line tells my ParticleComponent to add a particle at the specified position and initial velocity - replace it with your own particle code to get a nice stream of particles behind your car. I plan on adding a similar particle effect to the actual engine when the vehicle takes damage. For example, if the engine is emitting grey smoke, the damage to the vehicle is rather light. But if the smoke is black, the vehicle is heavily damaged and requires repair. The next particle effect I will be working on is adding a dust trail streaming behind the tires.


Change the Gravity 
       One thing I forgot to mention in my previous vehicle physics post was how I changed the gravity. Inside the Physics System Class (PhysicsSystem.cs), scroll down and change the gravity variable from -10 to -30. 

        public PhysicsSystem()  
        {  
            CurrentPhysicsSystem = this;  
            Gravity = -30.0f * Vector3.Up;  
        } 

This will make the car and the physics in general less like the "moon's gravity" and more like the Earth's gravity.


Add Rotational Friction to the Wheels
       Now open up the Wheels.cs file. Before, if you were on level ground, you could coast forever after letting off the throttle.

     if (driveTorque == 0)
    {
        angVel *= .97f;
    }  

Put this in Update() in the Wheels.cs right above angVel += driveTorque * dt / inertia:

                 if (driveTorque == 0)
                {
                    float axleFriction = 5; // higher number = more rotational friction
                    if (angVel > axleFriction)
                    {
                        if (angVel > 0) angVel -= axleFriction;
                        else angVel += axleFriction;
                    }
                    else angVel = 0;
                }

If you want to add more friction, multiply by a smaller number. For less friction, use a bigger number that's less than 1. Also, to help counteract any bumps on the track, I decreased the wheel's damping fraction.


Improve JigLibX's Performance 
       I have highly modified the Jiggle Physics Library to run on XNA 4.0 and MonoGame. I am extending and improving it in many ways. Many indie game developers chose BEPU rather than JigLibX when developing their games for Xbox 360. One of the major reasons why was the fact that JigLibX's performance on Xbox 360 was extremely slow which decreased the game's frame rate. To help with JigLibX's physics performance on Xbox 360 as well as other less advanced hardware, I am changing its foreach statements to for and I will be adding separate loading threads to help improve the low frame-rate issues. JigLibX also makes extensive use of the "float" object. I mention this because the Xbox 360 has some issues processing floating points. So I am changing out all the floats to avoid major physics performance issues.


How to Get Rid of of the Infamous Wobble at High Speed
       One of the major issues people encountered using JigLibX was once the vehicle got to a certain speed, it started to rock side to side, with no obvious way to stop it. Nikescar came up with a solution to fix this issue. If you would like to see this problem for yourself, adjust the wheelFriction to 5.0f and wheelDampingFrac to 0.3f. The car should start wobbling at max speed.

       Each Update( ) is called at a different time for each wheel. One wheel gets slowed down and the other wheels stay at the current speed. Next, the update from one of the three wheels from the last frame gets slowed down and the remaining wheels go at the same speed. If you do this sixty times a second, you will get quick declaration corners of the car causing the wobbling. After a lot of trial and error, here is how you can fix this.

This problem occurs when the andVel reaches maxAngVel in the Update( ) method of the Wheel.cs:

angVel = MathHelper.Clamp(angVel, -maxAngVel, maxAngVel);

Either delete or comment out this line and it will take care of the problem. However, this creates another problem because now you won't be able to set a limit for the top speed.

In the Wheel.cs, add this with the rest of them:

public float AngVel
        {
            get { return angVel; }

        }


Then just after this under PostPhysics( ) in the Car.cs:

for (int i = 0; i < wheels.Count; i++)
                wheels[i].Update(dt);


add this:

for (int i = 0; i < wheels.Count; i++)
            {
                if (wheels[i].AngVel >= topSpeed)
                    destAccelerate = 0;
            }


This should fix it. Now you can freely setup your car without having to worry about the limitations of the infamous wobble. Lastly, to see how I implemented the skybox, check out my blog post here. Thanks for reading and if anyone has found this blog post helpful, please comment below.


Saturday, November 7, 2015

24. Game Project Sneak Peak and Terrain Engine Update



       Above is a sneak peak of some 3D models for my long-term game project I am working on. The following footage is still in very early stages of development. The textures for many of the models is simply a starting point. I will eventually use Substance Painter to texture the models to achieve much better results.

Home Concept Art Screenshots
Home Concept 1














Hotel/ Saloon Concept Screenshots
Hotel Concept 1





























Bus Home Concept Screenshots
Bus Home

Bus Home Top View


Bus Home Front Close-Up


Bus Home Front


Bus Home Back


Bus Home Bottom (Ground Level)


Outhouse Concept Art Screenshots
























Watchtowers
Outposts & Watchtower WIP

Go Carts
Go Carts are built primarily as toys for kids to drive around in.
These electric vehicles are built from scrap parts.
The fire extinguishers are used to give the vehicle an extra boost.


Vehicles

       I have been working on a tremendous amount of 3D models to create more content for my game projects. I don't have enough time to showcase them all here in this post, but they are still very early in development. Above is a brief glimpse of a concept quad car I put together. 


Robots
There are a variety of robots in the game. Most are NPCs








       The Cyclone Game Engine now has the ability to generate a terrain landscape by reading a bitmap and using the intensity of its pixels as height values. I found that the heigthmap processor that comes with JigLibX was similar to the XNA Generated Geometry Sample. A custom content pipeline processor converts the heightmap in 3D geometry. The game engine also supports Billboarding which is both a fast and efficient way to render lots of grass on the terrain. To save memory, the grass is actually 2d images rendered in 3D. The grass moves depending on the speed of the wind. As you can see in the video, I also got snow working which is also effected by the direction and speed of the wind. The snow effect is implemented as a 3D particle by using point sprites. I am working further on the game engine’s weather component and possibly a day and night system. Weather effects can help contribute to the atmosphere of the game since it is mostly set in an outdoor world. 



       Lately, I have been making improvements to my terrain. I am working on shader effects for my terrain and applying better textures and lighting. This is my terrain for planet Mars in the following image above. 



       The foundations of the Cyclone Game Engine's Physics System is coming along. Above is a screenshot of the collision skins. It's a pretty complex system. The red outlines for the track indicates that the model is static. 















Driving in first-person perspective is coming along. I am still making adjustments.