texts: Efficient dynamic character shadows [SW Rasterizer]

texts:
I am working on a SW rasterizer for a quarter-century old console (think sub-100 MHz RISC CPU, no dedicated 3D HW, couple megs of RAM) and am approaching a stage where I will be adding dynamic character shadows. It's a next-gen engine for the platform, so there are no known or proven approaches. Basically, render stuff as fast as possible - e.g. in least amount of instructions (and least amount of RAM access).

The biggest performance bottleneck of the platform is memory read / write(e.g. fillrate). The RISC can do almost all instructions in 1-3 cycles (except division), but anything requiring access to main RAM is 10x slower (than from small cache).

I am not looking for some generic shadowing solution (I wrote few for PC/XBOX-using Shadow Volume and Shadow Mapping, so I have an idea how shadowing works). I am alright with writing multiple codepaths for multiple scenarios (e.g. one for characters, another for static objects).

Known limitations:

No Z-Buffer
No Stencil Buffer
Target resolution : 320x200
Shadows can be black (no need for transparent shadows)
A fallback shadowing solution is having pre-rendered shadows from each animation frame into texture and just drawing the texture below character (but it looks too lame). It's possibly the fastest solution, though (rotate shadow bitmap and just blit the texels)

Considering the above limitations, I have chosen the technique of transforming the character mesh (a low-poly version of the original mesh) onto the floor plane (from the position of the light) and drawing the shadow mesh on the floor (with black color). This should result in the desired sharp shadows without any pixelation effects (unlike shadowing methods based on projecting a shadow texture).
But it will provide an effect of shadow being very large initially, and as character walks around, the shadow shrinks (until he is right below the light source) and then the shadow grows again.

Advantage:

Generic : If need be, I can apply it also on the walls, not just the
floor
Fast : Transforms are fast on the RISC

Disadvantage:

Overdraw : I expect a major portion of the floor to be covered by
the shadow (lightpos will be tweaked accordingly, for the sake of
the effect). Since shadow is black, all the expensive lighting
calculations on the floor are wasted, since they are [mostly]
overwritten by the shadow.

The floor (basically one large rectangle) is internally divided into multiple square tiles (anywhere between 10-100 tiles per room). I think I can easily find out which floor tiles will be affected by shadow (I will calculate them during projection of the mesh onto the floor).

Question - how can I easily merge the floor texturing routine with the shadowing ?
Ideally, each texel would be written just once. There are just two choices - either it is a floor texel or black (the shadow).

Anything - that merges the two approaches into one which will be faster than rasterizing a floor and then overdrawing majority of it with black shadow- is a win. Ideas ?

The most amount, I could theoretically spare, from the tiny cache (10x faster access than from main RAM) is about 1-2 KB for a temp buffer. Obviously, it is not enough to cover all shadow texels at given resolution, but it could perhaps prove useful for some other algorithm.

As of right now, I can only think of span buffers as the best solution for the overdraw. The spans would be short (e.g. easily fit into 1-2 KB), I just would have to rewrite the floor texturing algorithm - but if it was a faster solution, I could do that.

Any other ideas ?


texts: Using C++11 for cross-platform Game Engine Development

texts:
Note: This is not a 'give your opinion' question about C++03 and C++11.

Our game engine, written in C++03, is designed to be compiled on Windows, OSX and iOS. Linux support is planned for the (very) near future. Our experience is limited when it comes to consoles, which is why I am asking this question.

Currently, we are debating whether switching to C++11 and using non-compatible features of the C++11 standard could pose a problem in the near future when we need to port our engine to any of the current gen consoles (perhaps the compilers supported by some console(s) do not support C++11 yet? We don't know...).

So, game developers who have experience across multiple platforms and consoles, do you think we should stick to C++03 until the new generation of consoles arrive and most everybody has switched to C++11 standard (have they already?). Or are most consoles using/support compilers (VC++, GCC or variants?) that are already supporting C++11 features?


texts:
I have to implement cron jobs in to my MMO browser game.
Its like in Travian game - you build something, and wait few minutes or hours..
But the problem is, that cron job shedulers made to be sheduled every second/minute/day etc..
But in my game i need to shedule thousands of the same jobs, which must run separately and after some unique time to be released.
So far i am unlucky with that idea. I am using Node.js and I just tried so many node shedulers, they seem are not supposed to have thousands of jobs.. I can run few unique only.
I trough maybe then i can make like - cron job, which runs every 1 second and checks the Redis DB for any finished proccess. But that sounds crazy.. if i have few jobs only and they are in 24 hous only, my server checks that every 1 second.. Any ideas what should i do?

So far, the best option would be to remove cron jobs.
I was doing some my processes without cron jobs.  But other processes were really hard to calculate, and it was much easier with cron jobs. But i trough deeper and i think it is possible to calculate eveyrthing and simulate everything without cron jobs.

For example, the user has ressources inside Stats model. And i have hourly ressource income there. If the user wants to build anything, for example, traps, i have to recalculate the user ressources and save new value, set the new updatedAt.
This is how i am updating my user ressources (inside Stats model), when some user wants to build a trap.

Stats.findOne({user_id: user_id}).exec(function (err, newstats){
  var time_in_ms = (new Date()).getTime() - new Date(newstats.updatedAt).getTime();
  var ressources_per_second = (newstats.base_income + newstats.field_income) / 60 / 60;
  var current_ressources = newstats.resources + parseInt(time_in_ms / 1000 * ressources_per_second) - traps_price;
  if(current_ressources < traps_price) return res.ok();
  Stats.update(newstats.id, {resources: current_ressources});
});


texts: How to fix this issue with point lights ?


texts:
I am messing around with Game Maker in my free time. I learned some Java at school but never really understood the object oriented principles. When I got to know Game Maker I was surprised that game development would be that easy. Game Makers scripting language is extremely easy to pick up and it's somehow "object oriented" design pattern is very easy to understand.
However there are a few bugs and ways to go in Game Maker I don't really like.
So as I'm using a Mac I started to learn Objective-C which also isn't that hard. The harder part would be getting to know Cocoa and when to use it's functions and which of them. Syntax is just syntax.
As Apple has now an own game framework "Sprite Kit" I'm curious if I should use that. I'm not even thinking about creating games full time for cash. It's just something I like to do in my spare time.
So when messing with Game Maker, you will probably see me trying to understand things like the Bresenham-Algorythm, how Springs in games work, which possible implementations of water there are and so on and further implementing these things into Game Maker.

I also compiled some of my Game Maker projects to OS X and recognized that these Game Maker exported projects eat up a big amount of CPU. I think that the export modules provided by Yoyo are not that great performance wise.
Moreover I think that Game Maker isn't a performance master at itself and thats just because how it works.
My first implementation of water was cell based. So in a grid of 120x80 "pixels" one cell represents a water "particle" that gets created by water spawners. This water object is then checking every step if it should fall or move left or right. Filling half of the screen which results in 3*4800 if conditions every frame lowered the frame rate from 60 to 20.
I know that that is not the best implementation. Every particle system can handle more particles without performance drops.
However I still think that there is a lot of overhead created by Game Makers architecture.

Water example:
In an object oriented language the object water_spawner would just initialize water objects out of the water class. The water class would still contain these conditions if it should move down left or right but that would be all.
I think that Game Maker objects are even checking for more that what is scripted in their step event. This is quite a workaround of an explanation but I think the point is clear. An engine where you could decide what an object will actually do could handle more water cells than Game Maker because of less overhead. Moreover if this engine is system native, the compilation would be "higher quality" I guess.

I know that Objective-C is not the fastest of all languages nor is Sprite Kit the fastest framework.
I'm just searching for something that is faster and more flexible than Game Maker and also OS X native. I don't want to spend time learning a framework which when able to work with it wouldn't be capable of handling bigger projects if I really wanted to create full games some day.
I know there is Unity which would probably a very good solution but then again I would have to learn C#.

So would a transition to Sprite Kit make sense? Or is Objective-C that slow that it and Sprite Kit wouldn't be faster than Game Maker?
Is it capable of handling bigger projects? I'm not talking about Crysis. I'm talking about 2, maximum 2.5D pixel art games but heavily rely on physics simulations or shader use.

So whats the best way to go in terms of performance? Objective-C with Sprite Kit or Unity, or would Game Maker still be faster?


texts: Just curious about it. I only want to know that what graphics API does the Unity web player uses. Is that WEBGL? Or simply OPENGL? Or A custom one? Then how do the games get gpu acceleration?


texts: How do I get the areas enclosed by an arbitrary 2D shape?

texts:
In my game I want users to be able to draw arbitrary 2D shapes of any length around game objects. The shapes must be closed and drawn with a single stroke that does not overlap.

For example:

I want to detect the presence of any game object in the green areas above.

I know how to detect whether a point is within a given polygon, but how do I tell where the polygons (green areas) are from just the points in the line?


texts:
So I'm playing around with the separating axis theorem and collision. Obviously the problem of what face it collided with arose. I need the unit normal which is tangent to that face it collided with to resolve depth penetration. For rectangles it's easy.

Update Y velocity
If collision
    collision happened on the y axis.
Update X velocity
If collision
    collision happened on the x axis.

But I wanted a more general that would work with all cases. I came up with two solutions

1.) So I thought about the solution above with a triangle. Obviously it wouldn't work because the rectangles faces are axis aligned and a triangles faces are not. So I figured I could just project the face and velocity using the dot product to solve it like the rectangle but for every face with its own axis. This would of course involve checking collision with the whole shape again for each face.

2.) I also figured I could do Polygon v Ray collision detection to figure out what face it collided with.

My question is: Which solution is faster? Or is there a better one that hasn't come to my mind?

I don't know how to do Polygon v Ray collision but I would guess that foreach face, find intersection point between ray and segment of face.


texts: Unity: Best Practise to apply Uniform Acceleration (regardless of direction)

texts:
I have read a lot of other topics both on here, on the Unity forums and from Google searches that answer thing that are similar but not quite the same as my question.

My question:

I have a Unity project with a sphere, the sphere starts at a certain initial speed and I want the sphere to accelerate uniformly over time to reach its maximum speed, regardless of bounces and interactions.

Obviously an interaction will cause the Velocity to change, but I don't want the Speed to change.

I started off looking for a speed LERP, but come up with the below code.

I have negated and turned off all drag and friction settings on the gameobject.

My current code is thus (C#):

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {
    public float accelerationSpeed = 10f;
    public float maximumSpeed = 25f;
    public float initialSpeed = 10f;
    private Rigidbody rb;
    private bool ballInPlay = false;

    // Use this for initialization
    void Awake () {
        rb = gameObject.GetComponent<Rigidbody>();
    }

    //...other functions that don't relate to this question...

    void FixedUpdate ()
    {
        /***
         * Gradually increase ball speed
         ***/
        if (ballInPlay == true && rb.velocity.magnitude < maximumSpeed)
        {
             rb.AddForce(rb.velocity.normalized * accelerationSpeed, ForceMode.Acceleration);
        }

    }
}

This code takes ~3-4 seconds to accelerate the ball up to the maximum speed, and it seems to adequately bounce the ball off rigidbodies, as I want.

However, I will in time be having more things interacting with the ball including explosions and other actual Force values (such as Wind), so taking this into account; is this code the best way of applying a constant acceleration to a game object, regardless of its other behaviours and influences?

While the above may work I'm also looking for best practise as far as possible (and memory/processor efficiency if that's applicable).

While obviously there are going to be unknowns (as it's excessive to show you my whole project, just for this qustion), some guidance on best methods of approach to solving this as well as improving efficiency would be appreciated.

Many Thanks.

EDIT:
To clarify my exact question:
Is the code above best practise when applying uniform acceleration to the gameobject while dealing with the influence of additional Rigidbody.AddForce functions on the gameobject.


texts:
I'm using a Unity Tilemap in my 2D game, and I have several hundred 32x32 sprites.  Most of the examples I've seen using sprites have a few consolidated sprite sheets that contain all of the game's sprites.  For instance, I'd have a few 1024x1024 sprite sheets that contain all of my game's sprites.
 Those examples all say that the reason to do it this way is that performance is improved when sprites are packed together like that.

The problem with these large consolidated sprite sheets is that it's difficult to find the sprites that I want when I'm making a tile pallet or animated/scripted sprite.

For example, I have two 1024x1024 sprite sheets called "House Interior 1" and "House Interior 2" that contain all my walls, floors, furniture, doors, windows, and miscellaneous interior objects.  Now I want to create one Unity tile pallet that has only tiles for western-style houses and one tile pallet that has only tiles for eastern-style houses.  Each tile pallet is going to require some, but not all, sprites from both of my sprite sheets (House Interior 1 and House Interior 2).  Additionally, I want to create some animated tiles.  Each animated tile will use a few sprites from somewhere in the middle of one of the large sprite sheets.

My problem is that each sprite sheet image has so many child sprites that it becomes very tedious and time consuming to visually scan through each huge sprite sheet to find the tiles I want, and then drag each of them individually onto my tile pallet.  Making animated tiles results in the same problem because when I assign each animation frame, I have to find the correct sprite from a huge list of sprites that are named House Interior_1, House Interior_2, House Interior_3, and so on.

I'd like to have smaller sprite sheets that only contain one specific type of sprite, rather than huge sprite sheets of often unrelated sprites.  For example, I'd like to have one sprite sheet that has only masonry walls, one that has only brick walls, one that has only the animation frames of a fireplace, and so on.  That way it'll be easier to build up Unity tile pallets by dragging several sprite sheets into the tile pallet in the Inspector, and it'll be easier to find my animated tiles because I can easily find the sprites named Fireplace_1, Fireplace_2, and Fireplace_3.

So my questions are:

How big of a performance hit will I experience if I don't pack my tiles together into a few big spritesheets?  Is it even worth taking this into account considering modern devices are so powerful compared to what is necessary to do sprite-based graphics?
Is this a case of balancing the pros and cons of both methods, or is it generally strongly recommended that I large consolidated sprite sheets?


texts: Preventing player units from pushing enemies, and vice versa

texts:
I am using a Rigidbody2D to handle collision between different units.
When the player's units encounter one another, they push each other because of the rigid body physics (and that's good for me).
But when the player unit encounters an enemy unit, he pushes it in the same way.
What are the solutions to make enemy's units unmovable by my units? (And my units unmovable for the enemy?)
(I know I could use isKinematic but I want the player's units to keep interacting with each other.)


texts: Unity2D: Wrapping a line around an object

texts:
I have this 2d platformer made out of box colliders. I have the player connected to a point by a LineRenderer and a DistanceJoint2D, for use in physics puzzles. This tool lets him link to a location and then do grappling hook things with it, like retract the rope at speed to spiderman around.

What I want to do is move the distance joint around the object, thus changing the angle at which the player is pulled. Like in this image.

Very similar to this more general, unanswered question that doesn't not give any specific math.

I know I'll be making a list of positions and then move the joint's anchor around whenever it wraps/unwraps, but I'm not sure how to tell when and where it wraps on something.


texts: How to fix this elbow issue when converting to humanoid

texts:
Good day, how can I fix this? it looks fine in Blender and generic but not when I switch to humanoid. There is no error on rig tab but there are in animation tab under the import message that say "is in between humanoid transforms and has rotation animation that will be discarded" and I can't seem to fix it.
Here are the things I've tried so far:

Put the right bones to the right slots.

Enforce T-pose.

Translation DoF.

Clicked Generate Retargeting and applied it.


texts:
Do transparent pixels cause a stencil buffer operation (increment, decrement, etc.) to be executed?

My understanding was that only opaque pixels cause a stencil buffer operation, transparent pixels have no effect on the buffer. However in my application transparent pixels do seem to cause the stencil buffer to be written.

Do I have to set up a special blendstate in order to achieve transparent pixels to have no effect?


texts: Is there a way to use Post Processing Effects on Mobile?

texts: I tried to use the built in unity Post Processing stack, I simply just want a vignette effect for my game, but it when I tested it on my phone it ran < 25 fps, which is too low in my opinion. Is there a way to recreate the effect for better performance?


texts: Sprite Animation in Android with OpenGL ES

texts:
How to do a sprite animation in android using OpenGL ES?

What i have done :

Now I am able to draw a rectangle and apply my texture(Spritesheet) to it

What I need to know :

Now the rectangle shows the whole sprite sheet as  a whole
How to show a single action from sprite sheet  at a time  and make the animation

It will be very help full if anyone can share any idea's ,
links to tutorials and suggestions.

Advanced Thanks to All


texts:
Is there any good documented and simple Game engine for RTS games, especially for building DotA-like game?

I know I can use Crystal Space, Irrlicht or another Game Engine. But I need most similar game or engine to DotA gameplay.


texts: What design choice should I follow for client-server communication?

texts:
My game server currently launches a thread for each connected client, and handles all data exchange through that socket in a server-blocks-until-client-requests fashion. The problem derives from the blocking, since sometimes the client state should be updated upon server demand without a previous request from the client, which is incompatible with a blocking state.

I have done some research and come up to the next possibilities:

1) Open a second connection to the client, which will only be used for sending data to the client so it can update its state.

2) Use of non-blocking sockets.

3) Use of asynchronous server.

What is the most common design to tackle this particular problem?

2 and 3 seen in https://stackoverflow.com/questions/3895461/non-blocking-sockets


texts: JavaScript - 2D Top-down Tile Collision Detection

texts:
I am developing a small Top-down Game (Much like the old Zelda Games) and I'm having an issue in terms of Collision detection (The actual theory itself rather than assigning Tiles as solid, etc.)

I have a function called "checkTileCollision" which takes two parameters, X and Y, and is called through the Player's Move function. X and Y are the location of the player AFTER they have moved, as it's suppose to check the position the player is moving to for a solid Tile(s), and if it finds any, returns true to stop movement.

My Player is larger than a Tile (For examples sake, let's say each Tile is 32x32 and the Player is 26x60) and I need to know an efficient way to detect whether or not the player is attempting to step on to a Solid tile. The Player doesn't move on the Grid and is free-moving, so X and Y are true positions and not Tile co-ordinates.

Please note; I am aware of things such as Box2D but I'm wanting to do this without the use of third party libraries.

Any help is appreciated!


texts:
My current task is to make the camera follow the moving cube in a stable way where the camera won't get locked in the center of the object so it won't get dizzy once the cube starts to collide or fall down.

I have done the parenting right, I have named the cube as the player and then selected it as the Transform reference in the new component that I have created for the camera to follow.

But it just says:

  UnassignedReferenceException : The variable player of FollowPlayer has not being assigned.

and I am unable to get the right results. What should I do ?

Here is the C# script that I wrote:

using UnityEngine;

public class FollowPlayer : MonoBehaviour {
    public Transform player;
    public Vector3 offset;

    void Update() {
        transform.position = player.position + offset;
    }
}

My scene setup looks like this:

So I have un-parented the main camera from the player and it works perfectly fine but I still get the error, Have any ideas why?


texts: OpenXR device not present in Start or Awake methods in Unity C# script

texts:
I'm developing a VR game using OpenXR in Unity (specifically developing on a Valve Index). When I try to access the input devices through the InputDevices.GetDevices() function, I get 0 devices back when I call this function from my script's Awake() or Start() methods. But when I call the same function from my script's Update() method, I see all the devices (e.g. head set, left controller, right controller).
Why can't I see the devices in the Awake() or Start() methods?


texts:
What I'm trying to do is to make an edit-mode script that gets all off-mesh links and makes some of them bi-directional(depends whether a jump is possible).

My (obvious) attempt was:

FindObjectsOfType<OffMeshLink>();

However, it returns only the links I have created manually.

My question is the following: how to access the off-mesh links generated by unity in the baked NavMesh?

Any help would be greatly appreciated.


texts:
I am building a 2d multiplayer game with no physics and my own authoritative server. Already have all players getting synced each with other but their movement isn't so smooth yet.

Here is the mechanics:
- player clicks on the screen to move towards the mouse pointer. Client sends action + angle to server
- server calculate new position based on a certain speed and sends it back
- player then moves through interpolation

After reading a lot of articles and play around with few samples code, I still have my doubts about how to get the clock right on both sides.

Would the approach below be suitable for my type of game?
- Run the server at 1000/10
- Run the Client network loop at 1000/60 and the game loop at 1000/60

Also do I need a game loop running in the server at 1000/60?


texts: What kind of work is usually done by scheduled tasks

texts:
I was reading about how task schedulers work in game engines. What is unclear to me is what kind of work is usually scheduled inside these tasks.

Do engines usually tick an actor inside a separate task? And if that actor triggers a pathfinding request, would that be a subtask? Should a pathfinding task allocate its own memory or access a global navmesh data for example?

I guess what I would like are real life examples on how such parallel systems can and are used in practice. Maybe some best practices based on examples would be nice. Most literature I found was quite theoretical and left me with so many questions.


texts: What sprite size should I use for 2D game?

texts:
I try to create a 2D game for Android. It looks like Cut the rope (it isn't a clone but it have same level representation) if it has a value.
My problem that I can't understand that optimal sprite sizes I should use. I.e. what target screen resolution should I use to sprites didn't have anomalies on HD-devices (like Samsung Galaxy S7 and etc., phones and tablets)?

To make my question is clearer I ask about this 1 unit = X pixels for xxhdpi-screens. What is X?

P.S. Sorry if it's a duplicate I will be grateful for link on this post cuz I couldn't find it.


texts: How do I create a jet engine exhaust effect with a shader?

texts:
How would I create a jet engine exhaust effect, as shown in the image from Fzero GX below.

GLSL and OpenGL examples/solutions are prefered, though other resources are also welcome.

Requirements

The jet engine should have a straight exhaust flame, that does not bend when the vehicle turns.
Some color variations in the flame are desirable, due to flame temperature variations.
The flame is only seen in a view directly behind the vehicle, and slightly from the side.
The flame should move slightly and also become bigger/brighter when the vehicle is thrusting.
Performance is more important than physical correctness.

More inspirational images and a video of the desired effect:


texts:
I have looked through all of the android docs and many stack overflow questions, and I have a question on supporting multiple screen sizes. If I have some drawables, I know I need to put them in folders like these:

But does android make these folders for me? When I try copy and pasting my images into the drawable folder, I get something like this:

With no directory names. So do I have to manually make those directories, and then will android automatically pick the right image to use depending on the screen size?

I have the same question for the layout. For example, I know that to support many screen sizes, I need to put the layout in many folders like this:

But right now, my layout is like this:

So must I manually create each layout folder, and then copy and paste my current layout into the new layout folder, and then go into each layout, and render it until it looks nice on the android design tab of the XML? Then, will android pick out the best layout depending on the screen size for me?

Thanks so much,

I have been delaying making my app compatible in different layouts because of these questions, I hope they can get answered!


texts: Xcode project runs on device, but not simulator

texts:
I built a 2D game using Unity3d 5.1.1. When i build and run the project with iPhone connected, the game runs fine on the device. But when i select simulator instead of device, i get an error :
" does not have an architecture that  can execute" .
I run the game on iPhone 4S, but cannot run on the iPhone 4S simulator. Similarly, i selected iPhone 6, 5 etc and get this error every time.


texts:
I currently have a ship that can orbit around a sphere freely controlled by a joystick. There is a separate joystick that controls the gun and starts shooting when it is touched.

Right now the bullets start shooting and then orbit the sphere until their lifetime has elapsed. Instead of having them orbit the sphere I want them to orbit for maybe the first half of their life and then shoot off into space. Does that make sense?

It would give the effect of a kind of glancing off the atmosphere, instead of staying in orbit for the whole time.

I am working in Unity3D and using the RotateAround() method to get the bullets to orbit. I'm thinking I need to take a snapshot of there position at half life, and then figure out the vector that would shoot them off into space. If someone could help me get going in the right direction with that, that would be great!


texts: Best practice to store level data in a rhythm based game

texts:
Setup:

I'm planing to do a rhythm based game, where a level is a music score similar to Frets on Fire, but with real music.

I've two options to store that level data, namely a MIDI file and a MusicML file.

It seems that the defacto standard is MIDI files (see Sintesia, for instance).

I don't need to output that data to the audio system, since is only to build the gameplay, since the player will be the one that will produce the sounds with an external device.

Question:

I wonder, since MusicML is more structured and easy to interact to, if it would be best to store the level data as a MusicML file.


texts:
I created small game in Java using LWJGL 2.9.3 and would like to add it to webpage as Java applet. I have followed this tutorial and have used this app loader. All the Java code works and I can tun the applet in my IDE. However, when I try to run the applet in a webpage I get the following error:

  SercurityException

  attempted to open sandboxed jar http:// 127.0.0.1/lwjgl_util_applet.jar as Trusted-Libary

Any idea what is wrong and how may I fix it?


texts: XNA 4.0: 2D Camera Y and X are going in wrong direction

texts:
I asked this question on stackoverflow but assumed this might be a better area to ask it as well for a more informed answer.

My problem is that I am trying to create a camera class and have it so that my camera follows the proper RHS, however the Y axis seems to be inverted since on the screen the 0 starts at the top.

Here is my Camera2D Class:

    class Camera2D
    {
        private Vector2 _position;
        private float _zoom;
        private float _rotation;
        private float _cameraSpeed;
        private Viewport _viewport;
        private Matrix _viewMatrix;
        private Matrix _viewMatrixIverse;

        public static float MinZoom = float.Epsilon;
        public static float MaxZoom = float.MaxValue;

        public Camera2D(Viewport viewport)
        {
            _viewMatrix = Matrix.Identity;
            _viewport = viewport;
            _cameraSpeed = 4.0f;
            _zoom = 1.0f;
            _rotation = 0.0f;
            _position = Vector2.Zero;
        }

        public void Move(Vector2 amount)
        {
            _position += amount;
        }

        public void Zoom(float amount)
        {
            _zoom += amount;
            _zoom = MathHelper.Clamp(_zoom, MaxZoom, MinZoom);
            UpdateViewTransform();
        }

        public Vector2 Position
        {
            get { return _position; }
            set { _position = value; UpdateViewTransform(); }
        }

        public Matrix ViewMatrix
        {
            get { return _viewMatrix; }
        }

        private void UpdateViewTransform()
        {
             Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0)) *
                           Matrix.CreateScale(new Vector3(1f, 1f, 1f));

             _viewMatrix = Matrix.CreateRotationZ(_rotation) *
                          Matrix.CreateScale(new Vector3(_zoom, _zoom, 1.0f)) *
                          Matrix.CreateTranslation(_position.X, _position.Y, 0.0f);

             _viewMatrix = proj * _viewMatrix;

        }

    }

I test it using SpriteBatch in the following way:

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    Vector2 position = new Vector2(0, 0);
    // TODO: Add your drawing code here
    spriteBatch.Begin(SpriteSortMode.Immediate,
        BlendState.AlphaBlend,
        null,
        null,
        null,
        null,
        camera.ViewMatrix);

    Texture2D circle = CreateCircle(100);
    spriteBatch.Draw(circle, position, Color.Red);
    spriteBatch.End();

    base.Draw(gameTime);
}


texts: Game Development at iOS, Android and PC with OpenGL ES

texts:
I'm beginning iOS apps development, and my aim is to make games to launch on App Store.
But I want to know if it's possible to program a game on Xcode with OpenGL ES (C++ game logic), integrate it on iOS with ObjC, and with that same game code (OpenGL ES + C++), implement it for Android with Java and to PC.

I have great interest to publish the same game on App Store, Google Play and specially Steam, and intent to build my personal 2D engine/API when I have more experience on graphic programming.

Do you know where can I find material to learn this?


texts: algorithm advice for game background ambiance - animals living in forest

texts:
In the game, there is a forest and animals living in it.
The interaction of the animals is just a background ambiance.

When googling I found Goal-Oriented Action Planning pattern.

And this pattern seems to solve the issue. If we give goals to the animals while achieving their goals they can behave realistically for the ambiance.

After more research, I found a paper which is advising extending GOAP with smart ambiance objects to make agents behave context aware.
"Feeling the Ambiance: Using Smart Ambiance to Increase Contextual Awareness in Game Agents"

For example, think of an adventure game, the player is searching for clues/items in the forest.

Meanwhile, a bird (non-player character) is looking for a fruit on the tree to eat.
Bird sees a fruit on the tree but also saws a snake danger close to the fruit.
So bird afraid and do not decide to eat that fruit...

Are there other algorithms/patterns that you can remind to solve this need?


texts: Movement Issues: jumping to another GameObject

texts:
My code can make a GameObject jump while simulating gravity. Now I want my GameObject to jump. The purpose of this is to always have a nice "touchdown".

Instead of the parabola, I want to use my jump script but I want it to jump using this relation with the other GameObject. I also need it to work while the target point is moving.

Could anyone solve this problem? An answer would be greatly appreciated. If you've got any questions, do not hesitate to reply (I understand that it's hard to understand...).


texts: Should pathfinder in A* hold closedSet and openedSet or each object should hold its sets?

texts:
I am about to implement A* pathfinding algorithm and I wonder how should I implement this - from the point of view of architecture.

I have the pathfinder as a class - I think I will instantiate only one object of this class (or maybe make it a Singleton - this is not so important).

The hardest part for me is whether the closedSet and openedSet should be attached to objects that can find the path for them or should be stored in pathfinder class ?

I am opened to any hints and critique whatsoever.

What is the best practice considering pathfinding in terms of design ?


texts: How to achieve high Level of Detail on 3D models

texts:
I'm developing a 3D space-based game which allows free movement in all directions and features planets. Currently I am using the Visual Studio content manager to import models (spheres) with 2D textures applied to them. These planets are supposed to be very large, which allows the player to come very close to their surfaces.

From afar, the textures look great. Up close, however, they become very blurred or pixelated (depending on whether I draw them with linear or point clamp).

I understand that I can enable mipmaps for the textures to change the level of detail shown at different draw distances, but obviously this can only be as high resolution as the texture files I provide it. The Visual studio content pipeline only allows Texture2D of size 2048x1024 or less and obviously I don't want to be holding enormous image files in memory for use in game.

Should I produce a set of higher resolution tiles of small sections of the planet's texture, load them on demand and stitch them together? How would this be achieved in XNA?

The effect I'm looking for would be similar to google maps.

It may be that in the future, I will decide that the textures being blurred or pixelated is acceptable, but since this is much a learning process for me, I'd still like to know how it would be solved.

Below is a demonstration of what I mean using a Mercator map of the Earth as an example:


texts: Unity UI - Make text come out and go back in

texts:
In Unity UI I have a TextMeshPro Button and some TextMeshPro Text like in the following image:

Is there any function in a Tween Library like DOTween that could make the text look like its coming out from the left side then going back in? (not scaling). Or without a tweening library how could this be done?
Something like:

As @DMGregory pointed out, this could be understand in two ways

coming out and in letter by letter or
smooth transition, cutting the letters.

My aim was to achieve 2) - a smooth transition.


texts: Crafty.js multiplayer platform game, keeping players in sync

texts:
I'm using crafty.js to create a very simple platform game. It doesn't need to stop cheating, it's actually just seeing other players move around, and it doesn't need to have collision detection between players. They are "shadows".

How I've gone about it so far is to use http://pubnub.com to send messages between clients. These messages are simple. The first if a new player arrival, the second is a key down and the third is a key up.

The code is here: https://github.com/whiteoctober/craftyconcept

However I've hit against the old chestnut of keeping everything in sync.

At the moment I'm letting the each of the clients decide where to place the other players based on the received key events, I also only move "you" until I get a key press event back from pubsub. My thinking here is to try and keep things in sync!

However it isn't perfect, http://www.whiteoctober.co.uk/john/gametest/, things can get out of sync very easily. Key presses arrive in the wrong order etc.

Is there any simple solutions to this, I would like to keep it all client side (with pubnub) and not have a central server with positions etc if possible.


texts: The rule to scale pixel art non multiple of integer ratios

texts:
I have pixel art, I want to draw. When player jumping I want to animate the art to squash stretch to have a feeling. But when I scale the art it get's distorted, as demonstrated in the image.

In one video I heard a rule to always scale to multiples of 100% ratio. So 150% is not allowed otherwise pixels collapse into each other. I haven't experienced that in this image but is it ok to scale arbitrarily in pixel art?
I see they scale the sprite arbitrarily in Celeste Game Player source. But It feels wrong to me.


texts: What are the properties of "position, velocity, acceleration, rotation" collectively named?

texts:
They say naming things is one of the hardest problems in computer programming. They were right.

Given the pseudocode below, what is a more appropriate name for this collection of properties? "Course", "Route", "Heading", "Orientation" all don't capture it.

class NewtonianStuff { // <-- Needs a better name
  vec3 position, velocity, acceleration; // <-- What is this group called
  quat rotation;
};

class SpaceShip {
    NewtonianStuff xxxxxx; // <-- What do you call that
};

Perhaps that collection is too abstract. What is the formal name for this collection of properties?

vec3 position, velocity, acceleration;

The best I can come up with is "PositionAndDerivatives", which doesn't really flow.


texts: Still award achievements/badges on failing level?

texts:
I've got a simulation game where the player works through a series of missions/levels.

The player also earns in-level badges as he works through.

But, if the player fails a mission (and has to restart it), should the badges still be awarded?  Or should badges only be retained on successfully completing the parent mission?

Your thoughts are welcome.


texts: How can I "smoothen" my path-finding on a map with big tiles?

texts:
I've just implemented A* in my "game", but as I finished it this came to my mind:

This is fine for a turn based game, but it would be really annoying for a real-time one.

For example look at the picture below.

In an action rpg the character would move to its goal in a straight line, but this is impossible here because the tiles are too big to make a that straight line.

So my question is:

How do they solve this in action games?
(I don't think that they have miniature tiles because that's too inefficient. But maybe I'm wrong.)

Edit:

Or should I remove those tiles from path, which aren't necessary?

So there will be a only a few points left, which are connected by straight lines?

Like this: go through the path from the Start.

When I find a X. tile which can't be accessed with a straight line from start:
Remove every tile from the path between Start and (X - 1). tile.
Repeat this from the X. tile, till I find the End.
Interpolate through straight lines between the remaining points.


texts: How to handle transparent pixels in a spritesheet

texts:
I am trying to correctly handle transparent pixels. I have a spritesheet that gave me the following:

The green body is the ground physics body and the gray body around the sprite is the sprite's physics body - calculated with the bounds of the sprite. I plan on having images for the ground body of the same size, and wanted the sprite's feet to touch the ground. I was able to achieve this by repacking the images in a new spritesheet with TexturePacker, without any transparent pixels:

However, now my problem is other animations, like crouch for example:

As you can see, the sprite's feet are once again off the ground. Doing this animation in the game looks silly because the sprite crouches by lifting his feet off the ground body.

The output metadata in JSON from TexturePacker looks like this:

{
    "filename": "Crouch/soldier_crouch_1.png",
    "frame": {"x":712,"y":867,"w":353,"h":425},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":49,"y":42,"w":353,"h":425},
    "sourceSize": {"w":433,"h":500},
    "pivot": {"x":0.5,"y":0.5}
},
// ...

This is a problem for several of my animations with this and other sprites. Repacking with TexturePacker allows me to remove the transparent pixels and have a more accurate physics body (which was really the goal, I'd like the most accurate collision detection once I start having projectiles) but now the animations look funny.

How is something like this handled in game development?


texts:
I'm using C# code to make a responsive GuiText.
I was abel to make a responsive GuiTexture, but I'm struggling with doing the same for a GuiText.

Code for the responsive GuiTexture

using UnityEngine;
using System.Collections;

public class ResponsiveGUITexture : MonoBehaviour {
    public float designScreenWidth = 800, designScreenHeight = 480;
    public bool debugMode = false;

    private Rect pixelInset0;

    void Start () {
        pixelInset0 = this.guiTexture.pixelInset;
        this.guiTexture.pixelInset = new Rect(Screen.width / designScreenWidth * pixelInset0.x, Screen.height / designScreenHeight * pixelInset0.y, Screen.width / designScreenWidth * pixelInset0.width, Screen.height / designScreenHeight * pixelInset0.height);
    }

    void Update(){
        if(debugMode){
            this.guiTexture.pixelInset = new Rect(Screen.width / designScreenWidth * pixelInset0.x, Screen.height / designScreenHeight * pixelInset0.y, Screen.width / designScreenWidth * pixelInset0.width, Screen.height / designScreenHeight * pixelInset0.height);
        }
    }
}


texts: Projectile movement around spheres of varying gravity

texts:
I found a game on the Internet called Sagittarius. This game is very fun, and I have a question: how can I make the arrow move like it does in this game? I know each sphere has a different gravity, but when I try to use this formula, it's not working as I expect=. Can any one help me resolve this problem? Thanks.

  public List<PlanetABC> p = new List<PlanetABC>() {
    new PlanetABC(){
        x = 0.91f,
        y = -1.28f,
        gravity = 5,
        r = 5
    },
    new PlanetABC(){
        x = 8.12f,
        y = -1.3f,
        gravity = 3,
        r = 10
    }
};
void Start () {

}
void Update () {
    float gravityOnX = 0;
    float gravityOnY = 0;
    foreach (var planet in p)
    {
        if (Vector2.Distance(g.transform.position, new Vector2(planet.x, planet.y)) > planet.r)
            continue;
        if (planet.x > g.transform.position.x)
            gravityOnX += planet.gravity;
        else gravityOnX -= planet.gravity;

        if (planet.y > g.transform.position.y)
            gravityOnY += planet.gravity;
        else gravityOnY -= planet.gravity;
    }

    if (currentGravityX > gravityOnX)
        currentGravityX -= Time.deltaTime;
    else currentGravityX += Time.deltaTime;

    if (currentGravityY > gravityOnY)
        currentGravityY -= Time.deltaTime;
    else currentGravityY += Time.deltaTime;

    Debug.Log(currentGravityX + "/" + currentGravityY);
    var DEG2RAD = Mathf.PI/180;
    float vx1 = Mathf.Cos(angle * DEG2RAD) * power ;
    float vy1 = Mathf.Sin(angle * DEG2RAD) * power;
    float y = (0.5f * currentGravityY * time + vy1) * time;
    float x = (0.5f * currentGravityX * time + vx1) * time;
    Vector3 pos = g.transform.position;
    pos.x = x;
    pos.y = y;
    g.transform.position = Vector3.Lerp(g.transform.position, pos, Time.deltaTime);
    time += Time.deltaTime;
}

Here is the game: https://gprosser.itch.io/sagittarius


texts: How to implement a pannini projection in opengl?

texts:
I have read about the pannini projection, which involves (I think) projecting a scene onto a cyclinder instead of a rectangle.

How can I implement this projection in a vertex shader?

Blinky is using lenses and globes, but I don't think it's what I am looking for. The lua script for the pannini projection is not commented https://github.com/shaunlebron/blinky/blob/master/game/lua-scripts/lenses/panini.lua

As explained on http://tksharpless.net/vedutismo/Pannini/ the projection works (if I understand it well), by projecting geometry on a cylinder, and then unrolling that cylinder on screen.


texts:
My end goal is to play a card game with my friends from other locations over the internet. I am going to start with a card game like blackjack and want people to be able to play in real time or close to it. I am not really sure where to start here and in which language. I was kind of thinking of making a website that can do this but I am not really sure. My end goal is to play MTG with friends and build decks.

Any ideas on a language to choose or where to get started? My current plan is C# asp.net webforms... Would Java be a good idea? I dont need it fancy, just functional. I am good at C and C# and some Java.

Thanks.


texts: Manage user input and diffentiate it between the player and the app

texts:
I hope the title makes sense. Basically, I am trying to figure out how the app will know I the input I am sending it is meant for the app and not the player, and vice-versa.
(It is very similar to this question, A pattern for a contextual InputState in a Game State Management architecture)

This is an idea I've had, but it's flawed. Any suggestions?

There will be a class to gather input, called IOManager
Another class will register the IOManager, called IOHandler.
Various subclasses of the IOHandler will handle the output differently. For example, IOPauseState will handle input differently than IOTitleState or IOPlayer

My problem comes with differentiating between the "GameStates" and the "Player" when handling the IO. I could have two separate HandleInput functions in the IOHandler class; one that accepts a reference to a state and another that accepts a reference to the player, but that does not seem right.

How should I go about handling this, when I can't really subscribe them or pass them through because the player and the gamestates are two completely separate classes?


texts:
I've been trying to make a soundmanager recently which has several functions which fits my needs. But one thing I can't solve, is the offsetting the soundeffects.
Is it possible to play a soundeffect from a specific point? I know I have to use the buffering, but I couldn't find anything on the net about it. Any help would be appreciated!


texts:
I'm developing a 3D game engine in C# and I was just wondering what are the different ways I can approach designing a graphics API abstraction.

My original design was going to be something like this:

public interface IVertexBuffer : IDisposable
{
    void Bind();
}

#if DRIVER_TYPE_OPENGL_45

public sealed class OpenGLVertexBuffer : IVertexBuffer
{
    public void Bind()
    {
        // Bind buffer...
    }

    public void Dispose()
    {
        // Delete buffer...
    }
}

#endif

#if DRIVER_TYPE_OPENGL_ES30

public sealed class OpenGLESVertexBuffer : IVertexBuffer
{
    public void Bind()
    {
        // Bind buffer...
    }

    public void Dispose()
    {
        // Delete buffer...
    }
}

#endif

In C#, sadly pre-processors don't work the same way they do in C++, so I would have to compile two versions of my project, but that just seems hacky and I would much rather be able to switch between drivers types.

So, I had another idea to do something like this:

public interface IRenderDevice
{
    IVertexBuffer CreateVertexBuffer(float[] vertexData, int sizeInBytes);

    void DestroyVertexBuffer(IVertexBuffer vertexBuffer);
}

public sealed class OpenGLRenderDevice : IRenderDevice
{
    public IVertexBuffer CreateVertexBuffer(float[] vertexData, int sizeInBytes)
    {
        // Create vertex buffer
    }

    public void DestroyVertexBuffer(IVertexBuffer vertexBuffer)
    {
        // Destroy vertex buffer, or should I just call vertexBuffer.Dispose()?
    }
}

and then just use an enum to determine which render device to create, but I know this solution will quickly get out of hand when I begin to introduce other things like vertex arrays, index buffers, frame buffers, etc.

What other options do I have that will still maintain readable code and look native to C#?


texts: Do glColorMask and glDrawBuffer accomplish the same thing?

texts:
I'm doing a shadowmap pass (only storing depth values) so I set glDrawBuffer(GL_NONE) to disable color writing for the moment.

Yet, I see some tutorials also do glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE). Is this really necessary, given glDrawBuffer(GL_NONE)? Don't they accomplish the same thing?


texts: How to solve the Google Ads problem in iOS?

texts:
Step 1: I'm implementing a Google AdMob using this link.

Step 2: When I import this plugin in unity->build(ios)-> and implement in xcode then  give this error: 'GoogleMobileAds\GoogleMobileAds.h' file not found

I'm tried this one for iOS
but the error is still not solved.

Reference:

GoogleMobileAds.h Not Found

I'm surfacing this problem the last 3 days - what is the issue with the plugin?


texts:
I have a 2d game (C++ and SDL) and I want the player object rotate to follow the mouse. The player object and the mouse location are both stored in 2d vectors.

In order to have the player's rotation look nice, I applied this lerp code between the "current" and "future" angle.

This is the function i'm using below, it should be straightforward:

void Vector2D_LerpAngle(const Vector2D& future, const float& dt, Vector2D& current)
{
    float a = 0.0f, b = 0.0f, c=0.0f;

    Vector2D_GetAngleDegrees(future, a);
    Vector2D_GetAngleDegrees(current, b);

    c = (a*t + b * (1.0 - t) - b);

    Vector2D_RotateByDegrees(c, current);
}

This actually works great - until the player rotates past 0 degrees. Then, it suddenly rotates in the opposite direction for almost an entire circle.

The only way I've been able to find to fix this is adding logic to catch the special case of being within 0-360 degrees, but to do that properly I'm going to have to take the velocity of the mouse into account, and that's just going to be a pain. I feel like I'm probably missing something obvious here or else I'm doomed to failure with this particular method.

edit:

It turns out lerping the vectors themselves rather than the angle works. I should have just trusted the math.

void Vector2D_Lerp(const Vector2D& future, const float& t, Vector2D& current)
{
    current = future*t + current*(1.0f - t);
}


texts: How to simulate an elastic force, using Hinge Joint ?

texts:
I've a bucket connected to a rope.

I would like that when a ball fall in my bucket , my bucket "bounce"down and up .. like it is connected to an elastic rope.

How can i do that ?

Thanks


texts:
So I basically want to load another map once the player collides with a object, specifically a "Portal" in my game. Which is really making the player move onto other levels. I don't want to jumble up my code with a bunch of function like "go_to_level_9" or something so I'm planning to use a list or dictionary or something. So how to those game devs out there do that? Code for main.py is here: https://pastebin.com/rpddq1MP. The part with the portal stuff, walls and a few others:
    for tile_object in self.map.tmxdata.objects:
        obj_center = vec(tile_object.x + tile_object.width / 2,
                         tile_object.y + tile_object.height / 2)
        if tile_object.name == 'player':
            self.player = Player(self, obj_center.x, obj_center.y)
        if tile_object.name == 'zombie':
            Mob(self, obj_center.x, obj_center.y)
        if tile_object.name == '#':
            Obstacle(self, tile_object.x, tile_object.y,
                     tile_object.width, tile_object.height)
        if tile_object.name in ['health', 'shotgun']:
            Item(self, obj_center, tile_object.name)
        if tile_object.name == 'portal':
            self.map = TiledMap(path.join(self.map_folder, tile_object.type))

how do you do it? I'm currently using Tiled and pygame so I'm also using pytmx.
Edit: When I run the code, it just gives me an error about my other file, tilemap.py.
Error:
File "D:\coding\my_coding_stuff\python\games\pygames\little rpg\tilemap.py", line 49, in apply return entity.rect.move(self.camera.topleft) AttributeError: 'TiledMap' object has no attribute 'rect'
Tilemap.py:
import pygame as pg
import pytmx
from settings import *

def collide_hit_rect(one, two):
    return one.hit_rect.colliderect(two.rect)

class Map:
    def __init__(self, filename):
        self.data = []
        with open(filename, 'rt') as f:
            for line in f:
                self.data.append(line.strip())

        self.tilewidth = len(self.data[0])
        self.tileheight = len(self.data)
        self.width = self.tilewidth * TILESIZE
        self.height = self.tileheight * TILESIZE

class TiledMap:
    def __init__(self, filename):
        tm = pytmx.load_pygame(filename, pixelalpha=True)
        self.width = tm.width * tm.tilewidth
        self.height = tm.height * tm.tileheight
        self.tmxdata = tm

    def render(self, surface):
        ti = self.tmxdata.get_tile_image_by_gid
        for layer in self.tmxdata.visible_layers:
            if isinstance(layer, pytmx.TiledTileLayer):
                for x, y, gid, in layer:
                    tile = ti(gid)
                    if tile:
                        surface.blit(tile, (x * self.tmxdata.tilewidth,
                                            y * self.tmxdata.tileheight))

    def make_map(self):
        temp_surface = pg.Surface((self.width, self.height))
        self.render(temp_surface)
        return temp_surface

class Camera:
    def __init__(self, width, height):
        self.camera = pg.Rect(0, 0, width, height)
        self.width = width
        self.height = height

    def apply(self, entity):
        return entity.rect.move(self.camera.topleft)

    def apply_rect(self, rect):
        return rect.move(self.camera.topleft)

    def update(self, target):
        x = -target.rect.centerx + int(WIDTH / 2)
        y = -target.rect.centery + int(HEIGHT / 2)

        # limit scrolling to map size
        x = min(0, x)  # left
        y = min(0, y)  # top
        x = max(-(self.width - WIDTH), x)  # right
        y = max(-(self.height - HEIGHT), y)  # bottom
        self.camera = pg.Rect(x, y, self.width, self.height)


texts: How can I make a tendril flame like aura visual effect?

texts:
I am a bit new to UE4 and I'm trying to get a tendril flame like aura like the picture below.

Does anyone know how I would go about this?

Should I use post processing or particles?


texts: How to unload/remove body components in Box2D?

texts:
I want to know how to release/clear/remove a variable. (specifically b2BodyDef, b2Body, b2FixtureDef, b2PolygonShape types.)

I've heard there's a keyword called delete, guessing by it's name it may have something to do with this subject?

I'm totally new to these things and I've just heard that there's a way to do this.

I might be wrong and there isn't a way to do this at all.

Which also means that I have no idea if I should include code or what information I should include at all :P


texts: tiled map - changing textures? (XNA HLSL)

texts:
I have successfully created a tiled map of various textures. Right now, i had a Vector4 in my own custom Vertex declaration deciding what texture each of the tiles should be. This is working perfectly. I can have any of my four tiles on the map, and any combination of them.

However, i would like to start having the tiles change, yet i do not know how to change this Vector4 of the vertices. They have been added to a vertex buffer if that helps you answer the questions.


texts: How can I adjust my code to make the objects start dropping at a certain speed and then increase that speed over time?

texts:
I'm making a game in LibGDX where the player dodges falling objects. At the moment, my code makes each object (in this case 'DROPS') fall at random speeds. I'm wondering if anyone can suggest how to amend this code to make all the objects start falling at the same speed and have this value increase over time. Here is my current code:

for (int i = 0; i < amount; i++) {
        float x = MathUtils.random(0, ManicMeltdowns.WIDTH - TextureManager.DROPS.getWidth());
        float y = MathUtils.random(ManicMeltdowns.HEIGHT, ManicMeltdowns.HEIGHT * 3);
        float speed = MathUtils.random(2, 5);
        addEntity(new Drops(new Vector2 (x, y), new Vector2(0, -speed)));
}

I assume you have to adjust 'float speed', but I'm not sure how.

Many thanks.

-Edit- Here is the drops class:

public class Drops extends Entity{

public Drops(Vector2 pos, Vector2 direction) {
    super(TextureManager.DROPS, pos, direction);

}

@Override
public void update() {
    pos.add(direction);

    if (pos.y <= -TextureManager.DROPS.getHeight()) {
        float x = MathUtils.random(0, ManicMeltdowns.WIDTH - TextureManager.DROPS.getWidth());
        pos.set(x, ManicMeltdowns.HEIGHT);
    }

}

}

And here is the entity class:

public abstract class Entity {

protected Texture texture;
protected Vector2 pos, direction;

public Entity(Texture texture, Vector2 pos, Vector2 direction) {
    this.texture = texture;
    this.pos = pos;
    this.direction = direction;
}

public abstract void update();

public void render(SpriteBatch sb) {
    sb.draw(texture,  pos.x,  pos.y);
}

public Vector2 getPosition() {
    return pos;
}

public Rectangle getBounds() {
    return new Rectangle(pos.x, pos.y, texture.getWidth(), texture.getHeight());
}

public void setDirection(float x, float y) {
    direction.set(x, y);
    direction.scl(Gdx.graphics.getDeltaTime());
}

}


texts: VBO = glGenBuffers() IllegalStateException

texts:
i'm kinda noob in OpenGL but I have this problem: I get an IllegalStateException at this code:

int vboVertex = glGenBuffers();

In-detail exception:

Exception in thread "main" java.lang.IllegalStateException: Function is not supported
at org.lwjgl.BufferChecks.checkFunctionAddress(BufferChecks.java:58)
at org.lwjgl.opengl.GL15.glGenBuffers(GL15.java:116)
at Mesh.initVbo(Mesh.java:49)

OpenGL version:
2.0.5819 WinXP Release

Thanks for support and sorry for the horrible english.


texts: How do I delete all saved preferences in my libgdx project?

texts:
I want to delete the preferences that saved my last highscore. How can I do this?

Here's how I am saving preferences at the moment:

prefs = Gdx.app.getPreferences("ZombieBird");
if (!prefs.contains("highScore")){
    prefs.putInteger("highScore", 0);
}

public static void setHighScore(int val) {
   prefs.putInteger("highScore", val);
   prefs.flush();
}


texts: Movement of an object based on thrust and gravity force in 2d scrolling game, need help

texts:
I want to make a box "fly" so while user press D it's add thrust then on A it decrese untill 0, W and S control the direction of my box.

I have problems after I add the gravity to update correctly my X and Y position.
My actual code is like this: (I'm using gamemaker but it's same as other languages, came execute 60 frames per second)

frametime = delta_time / 1000000;
spd = sqrt(power(velx ,2)+power(vely ,2));
tempgy = g * frametime ;
//tempay = ((thrust / m) * 32) * frametime; // or my box procede diagonally offcurse
tempax = ((thrust / m) * 32) * frametime;
y -= (vely + tempgy/2   + tempay/2 ) * frametime ;
x += (velx + tempax/2  ) * frametime ;
vely += tempgy + tempay;
velx += tempax  ;

m is mass of object = 500

g = 9.81

32 it's pixel per meter

So, basically I calculate the acceleration on gravity, and need to apply acceleration to x and y based on direction if I not understand wrong. So for the X component of thrust I have to multiply sin(degtorad(dir)) and for the Y must multiply cos(degtorad(dir)), but I have to apply the sin and cos only on acceleration?

I think I am doing it wrong because if I use g=0 and just using thrust my box act not as intended (ex: If I try to do a loop and stop accelerating my box will not follow the loop direction but continue on straight line)

Sorry for the stupid question but I really not know how to fix it. I see lot of tutorials with vectors but it's not supported here so can't use them. Thank you and best regards.


texts: Efficient sprite animation display methods?

texts:
I'm making a game sprite, with animations for transitioning to different states, such as idle, sleeping, etc. I'm wondering what the most efficient way to play the animations is. As of now, I have a couple of ideas:

store all frames as separate PNG images, and display only the frames for the current state (e.g. play frames 1-5 for idle, 5-10 for transitioning, 10-15 for sleeping)
make the animations into GIFs and play the one corresponding to the current state.
merge them all into a spritesheet.

Please let me know which would be the best approach, or if there's a better way to do things. I'm new to handling images and animation with code, so I'm not sure what the advantages and disadvantages are. Thanks!
In case the information helps anyone, I'm planning to use Python for this (although I could also do Java or C++, if there are good solutions in those languages), and the sprite image size isn't large, it's pixel art.


texts: How To Place Object On Ground Within Radius?

texts:
I'm using Unity and I'm building an object placement system where you'll be able to position objects around the player.

I'd like to place objects flush with the ground, parallel to world up, even on slopes, so I'll use a raycast for that.

How would I limit the distance to maxDistance? I tried using ScreenPointToRay but the max distance on the raycast makes the movement of the object stop if the raycast doesn't hit.

As an example, If I'm looking down in front of me, the object i'm controlling should be at that position. However, if I'm looking straight forward into Infinity, the object should only ever be maxDistance away. If I rotate, the object should follow smoothly.

Thanks!

edit: here is a video of what I have now, but as you can see, the object gets stuck if the raycast doesn't hit anything - due to the maxDistance. It doesn't get stuck if i use Infinity for the ray distance, but then the object doesn't respect max distance like I want it to.
https://streamable.com/bacij8

Code snippet:
https://gist.github.com/zackperdue/270e9574bed4a937bef791fb41512291


texts: Game communicates with MongoDB in the Editor but not in WebGL build

texts:
I was trying to implement MongoDB in my Unity WebGL game and everything is working fine in the editor: I managed to insert and retrieve documents from my Mongo database with no issues.
Everything seemed perfect until I compiled the project and realized that my WebGL build won't communicate with my database at all!
I took a look at the console and I see this error:

MissingMethodException: Default constructor not found for type MongoDB.Bson.Serialization.BsonClassMap`1[[UserAccount, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]

I have no clue what's happening. I tried compiling the project for Windows/Linux and I got the same error, then I changed API compatibility level to 4.x and it was working fine on the Windows build, but not on WebGL ( API compatibility level=4.x is checked for WebGL build!)
Can someone lend me a hand with that?


texts:
I am creating a game in Unity 3D and I have recently come up with my own simple replay system. It works well except for one small problem: it doesn't always start off where I would prefer it to in the recording of the gameplay. Basically every replay should be 8 seconds long. All I am doing for my replay system is storing the position and rotation of all objects in the scene, since there are only a few, in an array and then playing them back once an even is triggered.

I have the logical idea of how I should pick a starting point for the replay to start playing. I have a counter that increments every time my StorePosition() function is called in FixedUpdate(). That counter essentially gives me the number of indexes in the array so I know how many positions have been stored in total. All I should have to do is take that number and subtract from it the number of iterations that would occur during the 8 second replay.

My issue is that if I do the math for this: FixedUpdate() is called every .02 seconds which equates to 50 calls per second which would mean FixedUpdate() should be called 400 times over the time of my replay. So should I just be taking that total length of the stored positions array and subtracting that 400 and that would be the starting position in the array to start my replay?

That is the way I work it out in my head but it doesn't seem to work out quite right in the game. My counter seems to get into the 4000s or more over the 8 second replay so just subtracting the 400 from it doesn't give me anywhere near the amount of the replay that I want to see.

Is my logic flawed here? Any ideas?

2/21/2016

Here is some code for an example of how I handle this:

static Dictionary<GameObject, Vector3[]> positions = new Dictionary<GameObject, Vector3[]>();
public static int positionFillLength = 0;
static int index = 0;

public void StorePositions(GameObject[] objects)
{
    foreach (var obj in objects)
    {
        if (obj != null)
        {
            if (!positions.ContainsKey(obj))
                positions.Add(car, new Vector3[10800]);
            positions[car][index] = car.transform.position;
            positionFillLength++;
            index++;
        }
    }
}

public void PlayReplay(int index, GameObject[] gobjects)
{
    foreach (var obj in positions)
    {
        if (Array.IndexOf(gobjects, obj.Key) > -1)
        {
            if (positions[obj.Key][index] != Vector3.zero)
            {
                gobjects[Array.IndexOf(gobjects, obj.Key)].transform.position = positions[obj.Key][index];
            }
        }
    }
}

So if I am storing values I just call StorePositions() at ever call of FixedUpdate() and send in the objects to get the positions of.

When it is time to play a replay, I just start calling PlayReplay(). I create an index that starts at size 0 and increments every time that PlayReplay is called, which will also be every time FixedUpdate() is called, and pass that along with the objects into PlayReplay().


texts: Using Chromosomes to Go from Input to Output in Genetic Algorithms

texts:
Lately I've developed an interest in AI and genetic algorithms. Specifically, AI that learns to do something completely on its own. For example, play a video game. I've seen AIs that start out playing the game with no knowledge of what any of the buttons do, the only information they are given is their position, velocity, and the solid tiles and entities near them. Eventually the AI learns to run and jump. Later on, it learns to avoid enemies.

I mostly understand how genetic algorithms work, but there is one thing I really don't get. The chromosome is basically the instructions for the AI, right? My question is, how do you use the chromosome of the AI to go from the inputs(the AI's position, velocity, nearby tiles/enemies) to the outputs(button presses)? I think this is called neural networks, but after researching for an hour or so I didn't really understand the concept. Is the answer to my question just a bunch of "if" statements?

if(enemyNear)
{
    if(chromosomeContents[0]==1)
        jump();
    else
        keepRunning();
}

That seems like it would be redundant, since you would have to manually program in all of the best solutions, right? I'm not sure; I feel like I'm missing something really obvious here. If anyone could explain this to me, that would be fantastic. :D
(Sorry if my explanation was confusing. I tried to explain the best I could.)


texts: Check if 2 objects with multiple colliders overlap using bounds

texts:
I'm writing a script which instantiates buildings in a scene, but in such a way that 2 buildings don't overlap with each other. Every building consists of approx. 10 parts, of which each has a box collider.
The way I do this is by first instantiating the first building and adding it to a list. In this example I instantiate 2 buildings.
By the way, this doesn't need to run in real-time, my intention for this is to press a button in the editor and have a lot of buildings instantiated at once.
        for (int j = 0; j < 2; j++)
        {

            if(j == 0)
            {
                _buildingList.Add(GameObject.Instantiate(GetBuilding(Vector3.zero), _parent));
            }

Now in this same for loop, I instantiate the next building, add it to the list and check if it collides with the previous building in the list, like so:
            else
            {
                _buildingList.Add(GameObject.Instantiate(GetBuilding(Vector3.zero), _parent));
                if (_buildingList.Count > 1)
                {
                    int amountOfRepositioningAttempts
                    while (AreObjectsIntersecting(_buildingList[_buildingList.Count - 1], _buildingList[_buildingList.Count - 2]) && amountOfRepositioningAttempts < 10000)
                    {
                        amountOfRepositioningAttempts++;
                        GameObject buildingToMove = _buildingList[_buildingList.Count - 1];

                        buildingToMove.transform.Translate(Vector3.right);

                    }
                }
            }
        }

As you can see I have a few helper methods, which look like this
public GameObject GetBuilding(Vector3 position)
{
    GameObject buildingToInstantiate = _buildingPrefabContainer.GetRandomBuilding();

    Vector3 lookDirection = Vector3.zero - position;
    Quaternion lookRotation = Quaternion.LookRotation(lookDirection);

    buildingToInstantiate.transform.position = position;

    return buildingToInstantiate;
}

And the method from which I get unexpected results:
public bool AreObjectsIntersecting(GameObject object1, GameObject object2)
{
    BoxCollider[] _collidersObject1 = object1.GetComponentsInChildren<BoxCollider>();
    BoxCollider[] _collidersObject2 = object2.GetComponentsInChildren<BoxCollider>();
    for (int i = 0; i < _collidersObject1.Length; i++)
    {
        for (int j = 0; j < _collidersObject2.Length; j++)
        {
            if (_collidersObject1[i].bounds.Intersects(_collidersObject2[j].bounds))
            {
                return true;
            }
        }
    }
    return false;
}

The intention here is that I go over each buildings collider, and if one of those colliders overlaps with one of the colliders of another building, then the building gets repositioned, and the check happens again.
But the method AreObjectsIntersecting() seems to always return true, and I don't see why.
I know this because
    int amountOfRepositioningAttempts

Always ends up being 10000, while the 2 objects should have stopped intersecting with each other after only a few iterations of moving them.
Can anyone help me out here?
Thanks in advance!


texts: How to handle grid snapping when the object is greater than the grid cell width and height?

texts:
I want to be able to move objects on a grid always by what the grid cell size is, and objects bigger than the grid size should not overlap.

The cube in this GIF below is snapping how I want (1 x 1).

If I then change the size of the object, it doesn't snap to the grid quite how I would like.  It snaps, but overlaps.  I don't want an object to overlap the grid cell.

The snapping code is pretty straight forward and has been posted quite a lot and seems to work fine.

pos.x = Mathf.Round(hit.point.x + (hitNormal.x * objScale.x)) * gridSize;
pos.y = Mathf.Round(hit.point.y + (hitNormal.y * objScale.y)) * gridSize;
pos.z = Mathf.Round(hit.point.z + (hitNormal.z * objScale.z)) * gridSize;

I was thinking that I need to somehow set a pivot  / anchor point, but I wouldn't want that to be one corner of the object, I was thinking somehow I could find the center of the object and work from there so it can snap correctly.  Not sure if this is correct, or how to work that out.

Edit: More code added to show how I am moving objects around currently.

Objects are placed in the world by ray casting.  I don't use any grid array to know the location of objects on the grid.

For placement testing (i.e object inside another) this is handled already but removed that part of the code.  For that I am doing a simple box overlap test which works nicely.

float gridSize = 1f;
Vector3 hitNormal = hit.normal.normalized;
Vector3 localObjScale = transform.localScale;

// - "Determine the minimum grid space this shape will use up"
// Objects will always be whole numbers.  i.e 2w x 1h x 1l (like second GIF)
int cellWidth = Mathf.RoundToInt(localObjScale.x);
int cellsHeight = Mathf.RoundToInt(localObjScale.y);
int cellsLength = Mathf.RoundToInt(localObjScale.z);

Vector3 objScale = localObjScale / 2f; // This sets the pivot to the center
Vector3 pos = Vector3.zero;

// Snap
pos.x = Mathf.Round(hit.point.x + (hitNormal.x * objScale.x)) * gridSize;
pos.y = Mathf.Round(hit.point.y + (hitNormal.y * objScale.y)) * gridSize;
pos.z = Mathf.Round(hit.point.z + (hitNormal.z * objScale.z)) * gridSize;

transform.position = pos;


texts: Are there ways to limit players other than a conventional currency system or a resource system?

texts:
I'm making a 2D strategy game. I want to create something unlike the current resource management type games I regularly see tagged as strategy.
My goals are:

To force the player to think about their decisions
To allow for experimentation easily and without sacrificing previous progress
To allow for multiple ways of solving problems presented in the game
To eliminate grinding simply because it won't work in whatever system I use

In effect, I want some way to limit the player and force them to make hard decisions, without using a commonly used currency or resource/crafting system, to cut down on grinding.
However, I'm actually having a little trouble implementing this sort of idea alongside the idea of progression.
My original idea was to introduce a cap on how many of each type of item a player could have at any one time. In effect, this introduces some elements of an open-ended puzzle game. However, this limits progression:

If the number of items the player can have increases over time, this means that each individual item's significance decreases over time. This has the effect of making decisions easier over the course of the game. Not what I want.
If the items get more powerful over time, then items acquired near the start of the game have no viability later on. I would like items to be at least partially viable at any stage of the game, to increase variety and make the game less linear. It turns the game into replacing old with new.
Only increasing the variety of items over the course of the game is a sure-fire way to lose players early if they believe they are not making progress.

My implementation is workable, but simply not good enough for my personal standards and goals.
Is there a better way to let limits, choice and progression go hand in hand?
I use the word "item" here not just to refer to items in game, but other things such as spells, moves, buildings, etc. that a player could acquire  and use in the game.


texts: Does LibGDX abstract OpenGL ES away or can I still use my OpenGL ES knowledge?

texts:
I've been learning OpenGL ES, and am now turning my attention to using LibGDX.

My main concern with LibGDX is, if needed, will I be able to apply my OpenGL ES knowledge to something if needed and essentially override bits and pieces of the framework, or does LibGDX essentially hide any implementations of OpenGL?


texts: Make UnityEvent wait for completion of method calls on listeners?

texts:
I am using the UnityEvent EventManager script from this post in one of my games.

I want to know how I can make Unity wait for all the calls to methods on the listeners to finish before moving on to calling the next event?

For example,

If I have a method somewhere in my code that contains:

 EventManager.Invoke("MyFirstEvent");
 EventManager.Invoke("MySecondEvent");

How can MySecondEvent be invoked only after all the listeners of MyFirstEvent have finished ?

The reason being that I perform an operation in one of the listeners of MyFirstEvent which is needed for an operation performed in MySecondEvent.

Alternatively am I best to use a coroutine and call the MyFirstEvent on the first frame and MySecondEvent on the following one just to be sure. I read that spawning costly actions over a few frames can reduce spikes in CPU usage. However is it best practice to do so, or is it likely to cause problems down the line ?

Thanks


texts: How to create fallout intensity on a generated mesh in Unity?

texts:
So I was able to generate a circle mesh in Unity to basically see the other characters when they are inside of it, and hide the characters when they are outside of it, and partially hide and show the character if they are partially in or outside of it. Below is an image of what I was able to generate, but the thing is, the edges are very sharp and I would like to have some Fallout Intensity on the mesh. Just like with Lights in Unity, where they have a fallout intensity at the edge of the lights.
Image of Generated Mesh

As you can see, the edges of the mesh are very sharp and thats not the kind of effect am after, I would like to add some fallout to that, and adjust it.
Here is The Code That Generates The Mesh
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class FieldOfView : MonoBehaviour {

    public float fieldOfView = 360f;
    public int numberEdges = 360;
    public float initalAngle = 0;
    public float visionDistance = 8f;
    public LayerMask layerMask;

    private Mesh mesh;
    private Vector3 origin;

    private void Start()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        origin = Vector3.zero;
    }

    private void LateUpdate()
    {
        GenerateUpdateMesh();
    }

    private void GenerateUpdateMesh()
    {
        float actualAngle = initalAngle;
        float incrementAngle = fieldOfView / numberEdges;

        Vector3[] vertices = new Vector3[numberEdges + 1];
        int[] triangles = new int[numberEdges * 3];

        vertices[0] = origin;

        int verticeIndex = 1;
        int triangleIndex = 0;

        for (int i = 0; i < numberEdges; i++)
        {
            Vector3 actualVertices;
            RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, GetVectorFromAngle(actualAngle), visionDistance, layerMask);
            if (raycastHit2D.collider == null)
            {
                // No hit
                actualVertices = origin + GetVectorFromAngle(actualAngle) * visionDistance;
            }
            else
            {
                // Hit object
                actualVertices = raycastHit2D.point;
            }

            vertices[verticeIndex] = actualVertices;

            if (i > 0)
            {
                triangles[triangleIndex + 0] = 0;
                triangles[triangleIndex + 1] = verticeIndex - 1;
                triangles[triangleIndex + 2] = verticeIndex;

                triangleIndex += 3;
            }

            verticeIndex++;
            actualAngle -= incrementAngle;
        }

        // We form the last triangle
        triangles[triangleIndex + 0] = 0;
        triangles[triangleIndex + 1] = verticeIndex - 1;
        triangles[triangleIndex + 2] = 1;

        mesh.vertices = vertices;
        mesh.triangles = triangles;
    }

    Vector3 GetVectorFromAngle(float angle)
    {
        float angleRad = angle * (Mathf.PI / 180f);
        return new Vector3(Mathf.Cos(angleRad), Mathf.Sin(angleRad));
    }

    public void SetOrigin(Vector3 newOrigin)
    {
        origin = newOrigin;
    }
}

What do I do here to add some Fallout Intensity? All the help is really appreciated. And Thank you in advance.


texts: Box2D : rotate and set position to a static body with another origin

texts:
I try to rotate a static body of a PolygonShape, from another origin, and set the position regarding this new origin.

Why ? Because I create bodies from TiledMapEditor object. And origins of objects in this editor are in the left upper corner.

Regarding the documentation, I can set origin using the setAsBox method. But then when I set the position, the body is not where it is supposed to be. (an offset is apply between the current position and the expected position)

I assume that the origin is used for the rotation, but not the position.

How can I set the position from another origin, and rotating from this same origin ? (the upper left corner and not the center of the shape)

My attempt :

  val rotation = 45f // rotation angle (in degree)
  val shape = PolygonShape()
  shape.setAsBox(rectangle.width*0.5f, // half width
                rectangle.height*0.5f, // half height
                Vector2(0f, rectangle.height), // new origin
                rotation * MathUtils.degreesToRadians) // angle to radians

   val bodyDef = BodyDef()
   bodyDef.type = BodyDef.BodyType.StaticBody
   bodyDef.position.set(rectangle.x, rectangle.y) // set the position

Regards


texts:
I have recently been working on a small game project and decided to implement settings loading at game startup. The problem is that my method seems to be too hard coded and not scalable without having a huge method:

public String loadSettings(String path) {
    String[] file = loadFileAsString(path);

    isFullscreen = Boolean.parseBoolean(file[0]);
    windowWidth = Integer.parseInt(file[1]);
    windowHeight = Integer.parseInt(file[2]);
    ...
}

As you can see, this method will get very large after a while and is at risk of crashing if someone edits the file incorrectly so what is a better way of loading this data?


texts:
I have created a particle system.
In this particle system, I'm using a cylinder as a mesh.

It looks as I want it to, but its location is really strange:

In this screenshot one can see that in the Scene View window, there's a wide gap between the cylinder and the edge of the platform, and in the Game View window, there's no gap at all.

When I look at it from the Top View, it looks completely strange: It looks as if the cylinder was laying on the floor.

What is going on here, and how could I reliably place the particle system / the cylinder in my game at a certain location?

Thank you.

Edit:
This is my setup:

Edit: I have recorded a video here to show the Gizmos:
Unity Window


texts: Can someone explain to me the difference between 2 XNA methods?

texts:
I was recently trying to make a boucing ball off the environment walls. I apparently had everything correct, except for one thing, that I corrected stupidly, which made my code work, but I don't understand why.

So I had set the value of a 2d vector's X and Y inside protected override void Update(GameTime gameTime); this vector was what I would add to the object's X and Y so it could move according to whatever logic.

But it didn't work, the fix to this problem was to apparently declare the vector's values inside protected override void LoadContent().

So can anyone explain to me, what is the difference between declaring your variables/constants inside these two methods? And why?

EDIT : Wrong Sourcecode :

  protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // Loaded content
}
 protected override void Update(GameTime gameTime)
    {

        // Allows the game to exit
        if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape))
            this.Exit();

         //Code logic

            movement.X = 5;
            movement.Y = 5;
            birdbox3.X += (int)movement.X; //this variable was declared outside of any local field as a rectangle

            if (birdbox3.X <= 0)
            {

                movement.X = -movement.X;
            }
            else if (birdbox3.Y <=0)
            { movement.Y = - movement.X;
            }
            base.Update(gameTime);
        }

So when I would run this code, the birdbox3 would just stop when the if statement is fulfilled. The correct version would be to cut the

            movement.X = 5;
            movement.Y = 5;

and paste it into LoadContent() instead. The problem is I do not know why.


texts:
I created block of 3x3x3 cubes, disabled shadows, set directional lighting color to white and ambient to black. And I'm getting this:

Any idea what is going on and how to fix it? Effect is visible when object isn't moving but with a lot less artifacts. It doesn't matter what is moving, camera or cubes. I would guess that this is precision problem but is there anything that can be done about it?

//EDIT

Here is a screenshot of cubes:

Also this is how it looks after static batching (this happens because of Lightmap Static in Mesh Renderer is on):


texts: How Industy games handle their code errors and exceptions

texts:
I've seen games crash and throw errors.
Usually games don't throw raw exception message, but codename error names, such as F204 or similar. I would like to know some thought about that.

Also, as i understand they separate errors in non critical on which maybe some message is shown and there are critical on which game is shut down and error window pops up.

Example, this is how i see it

//Some actions
try{
    Bone bone = character.bones.Get(5);
}catch(ArgumentOutOfRangeException e){

    //show error - stack trace, message, or code name error
    ExceptionHandler(e.ToString(), ErrorType.CRITICAL); //handles

    //also could be, or similar
    ExceptionHandler("V401", ErrorType.CRITICAL); //handles, this is shown in game
}

public Bone Get(int index){
    if (index < 0 || index >= _someData.Length) throw new ArgumentOutOfRangeException("Index is out of range.");
    return _someData[index];
}

I think product users should not really see any exception logs but rather code names.
But what are the suggested management for this - error string manual pass like it did (but i don't think its manageable), constant in separate class, enums?

Edit:
Of course, having an error codename catalog would make the life easier for the devs themselves. If user submits an error, they can find the spot quite quickly. Does this made any sense?

Thanks


texts: How to "amplify" a force and physic using AddForceAtPosition?

texts:
I have the object in the image.

The red box is kinematic: when an object hit it , i set kinematic to false, so Unity apply normal physic.

But I would like to apply also a force to the point indicated by the violet cross.

So I'm using Rigidbody.AddForceAtPosition

_rb.AddForceAtPosition (ForceDirection * ForcePower, PointForcePosition.transform.position, ForceType);

PointForcePosition is an empty GameObject child of the red box object, placed where violet cross is pointing.

My question are:

Force Position: can I use that approach (an empty gameObject placed where i want to apply force ) ?
Force Direction: is it corret a Vector3 ( 0 , -1 , 0 ) to indicate a down force
Which ForceMode is the best for my purpose ?  Impulse ? Force ?

Thanks


texts: Standard Asset package import in unity 2018.3

texts:
I am using iMac, I don't see any for import standard package in unity. My working project need to import standard packages. I use unity version unity 2018.3.0f2. Please guide me from where I get the unity standard asset package.

Thanks.


texts: Second pass in multipass effect is ignored

texts:
I am trying to render my vertecies in 2 passes, but it seems I am doing something wrong, because only one pass applying. I cannot make the second one work despite that second pass is applying.

Here is my code:

var effectByteCode =            ShaderBytecode.CompileFromFile(@"Content\Effects\SpriteBatchEffect.fx", "fx_5_0");
spriteBatchEffect = new Effect(this.graphicsDevice, effectByteCode);
pass = spriteBatchEffect.GetTechniqueByName("SpriteBatch").GetPassByIndex(0);
//Layout from VertexShader input signature
var passSignature = pass.Description.Signature;
layout = new InputLayout(graphicsDevice, passSignature, inputElements);

Effect code:

    Texture2D Texture;
    SamplerState TextureSampler;

matrix OrthoMatrix;

struct VertexInputType
{
   float4 position : SV_POSITION;
   float4 color: COLOR;
   float2 tex : TEXCOORD0;
};

struct PixelInputType
{
   float4 position : SV_POSITION;
   float4 color: COLOR;
   float2 tex : TEXCOORD0;
};

PixelInputType SpriteVertexShader(VertexInputType input)
{
   PixelInputType output;
   output.color = float4(0, 0, 0, 0);
   output.position = float4(0, 0, 0, 0);

   // Change the position vector to be 4 units for proper matrix calculations.
   input.position.w = 1.0f;

   output.position = mul(input.position, OrthoMatrix);

   // Store the texture coordinates for the pixel shader.
   output.tex = input.tex;
   output.color = input.color;
   return output;
}

float4 SpritePixelShader(PixelInputType input) : SV_TARGET
{
   return Texture.Sample(TextureSampler, input.tex)* input.color;

}

float4 SpritePixelShader2(PixelInputType input) : SV_TARGET
{
   /*return Texture.Sample(TextureSampler, input.tex)+ input.color;*/
   return float4(1,0,0,0);
}

technique10 SpriteBatch
{
   pass P0
   {
      SetGeometryShader(0);
      SetVertexShader(CompileShader(vs_4_0, SpriteVertexShader()));
      SetPixelShader(CompileShader(ps_4_0, SpritePixelShader()));
   }

   pass P1
   {
      SetGeometryShader(0);
      SetVertexShader(CompileShader(vs_4_0, SpriteVertexShader()));
      SetPixelShader(CompileShader(ps_4_0, SpritePixelShader2()));
   }
}

And how I am using it:

graphicsDevice.SetVertexBuffers(0, vertexBufferBinding);

     var technique = tempEffect.GetTechniqueByName("SpriteBatch");
     for (int i = 0; i < technique.Description.PassCount; i++)
     {
        var localpass = technique.GetPassByIndex(i);
        //if (localpass.IsValid)
        {
           localpass.Apply(graphicsDevice);
           graphicsDevice.DrawIndexed(indexCount, 0, 0);
        }
     }

Could someone point me why second pass is not apply? What I am missing here?
Note that I am not using SharpdDX toolkit - just plain SharpDX + C#


texts: Formula to convert zoomed in game space co-ords to UI

texts:
I need to come up with a formula to convert variable zoomed-in game space co-ords to UI co-ords. The engine I'm using is not traditional so there's no inbuilt function (convertToUISpace etc).
Now I have a feeling this is extremely easy, but I cannot get my brain to work the math...
It's a top down 2D game with 2 layers, game and UI. The screen is 640x360 res, but there is a zoom overlay on the game layer that can take it anywhere up to 400x225. The HUD layer remains the 640x360 res throughout though.
So I need to translate x,y positions on the game layer (at whatever zoom) to correctly position on the HUD. At the moment if I use exact co-ords they don't quite match up, unless the object is exactly in the screen centre.
Could anyone assist or clue me down the right path? I'm guessing I have to work out from the screen centre using the zoom ratio.


texts:
So, I need to use LShift to run, but I can't exactly figure out how to do so....
I don't know what to use....
Here my code:
using UnityEngine;
using System.Collections;

// This script moves the character controller forward
// and sideways based on the arrow keys.
// It also jumps when pressing space.
// Make sure to attach a character controller to the same game object.
// It is recommended that you make only one call to Move or SimpleMove per frame.

public class Move : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Transform charBody;
    private Vector3 moveDirection = Vector3.zero;
    public float mouseSense = 11f;
    public float runSpeed = 12f;
    public bool isRunning = false;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = transform.forward * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;
            moveDirection = transform.right * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        float MOUSEY = Input.GetAxis("Mouse Y") * mouseSense * Time.deltaTime;
        float MOUSEX = Input.GetAxis("Mouse X") * mouseSense * Time.deltaTime;

        charBody.Rotate(Vector3.up * MOUSEX);

    }
}

So, when left shift is clicked I want the speed to change to runSpeed...
Can I please have some help doing so?
Thanks


texts:
is there a way to split a .fbx model into parts, and move those parts individualy in XNA 4.0 ?

Thanks


texts: Multiplayer game with differently screen size

texts: I am making a classic ping pong 2D multiplayer and its run on full screen, but i have a problem that the ball touch the limits of screen to one player and other no. Any idea how to solve this ?


texts: How can I fire a bullet from an actor's position?

texts:
I want to shoot a bullet from an actor.

I know I need a location in space to fire a bullet from, which I've got in the form of a model set as an actor. Now I need to create a new object (in this case, a bullet) with the same starting coordinates as that actor and set its movement direction to be the direction the actor is facing.

(Imagine a gun, a bullet is to be created at the coordinates of the tip of the barrel and the bullet will move forward in the direction that the gun was facing).

I can't figure out how to get the gun to generate the bullet or how to set the speed of the bullet. How can I do that in Unreal?


texts: My polygons only register a collision if they are the same shape and directly over top of each other

texts:
I'm trying to learn about 2d polygon collision detection/handling and have ran into a snag.

After running through lots of tutorials and sample code I've attempted to implement my own polygon class and separating axis functionality.

I have two polygons of the exact same shape and size that I can move around the screen, but they only register a collision if they are directly (to the pixel) over top of each other.

I suspect the problem to be in my isSeparatingAxis() or flattenPoints() function, as I'm struggling with some of the math involved in those.

Here's the relevant stripped down code / working example
https://jsfiddle.net/gyngbo0d/


texts: How to apply Image effect only on specific part of objects?

texts: I need a way to censore part of characters' bodies like Cyberpunk 2077.this is mean I want to apply Image effect only to specific parts of bodies that you can see in the below Image: