texts: AS3 ScaleX is moving object across screen

texts:
I am trying to make an HP bar for my game. I have the code here

private var hpBar:Sprite = new Sprite();
private function drawHPBar(s:Stage):void{
    hpBar.graphics.beginFill(0xFF1717); //Medium Red
    hpBar.graphics.drawRect(620, 165, 152, 22);
    hpBar.graphics.endFill();
    s.addChild(hpBar);
    s.addEventListener(KeyboardEvent.KEY_DOWN, displayKey);
}

private function displayKey(e:KeyboardEvent):void{
    hpBar.scaleX -= 0.02;
}`

But when the hpBar.scaleX is decreased, the object shrinks and at the same time, moves left across the screen(stage). I am so confused because I saw videos on youtube about the scaleX and they don't seem to have a problem.


texts: Camera and Wall collision - is it possible?

texts:
I have seen a couple questions on similar subjects but none of the answers am I satisfied with.

I have a camera which follows a game object; the problem is that it can pass through walls and because of this, has the potential to show some areas that aren't meant to be seen.

I have my walls built using a mesh exported by Sketchup. So there aren't clean barriers that I can write in code. I'd much rather do it using the same physics system that correctly prevents my player object from moving through the wall.

Yet this doesn't seem to work. I try to put a collider on the camera, and also a rigid body, but it has no effect.

edit

here is a image of my camera's collider bounds - see how it is partly inside the wall?

The walls are imported from FBX and I generated colliders upon import, so it's a mesh collider.

I am using cinemachine for the camera script.


texts: OpenGL Texturing Isn't working: displaying just white

texts:
Basically, see the title: for whatever reason, I load a texture into OpenGL, bind it, draw a quad with texture coordinates specified, and the quad remains totally white regardless of what the texture is.

I have made sure that GL_TEXTURE_2D is enabled. I have verified (using glGetTexImage) that the Texture has the correct data in it (or, if not the correct data, data that should be visible, as the pixels have different values).

My glTexture2D function is called as follows:

        glTexImage2D(GL_TEXTURE_2D, 0, pixelFormat, this->width, this->height, 0, pixelFormat, GL_UNSIGNED_BYTE, &(pixelData[0]));

This is where pixel format is either GL_RGBA or GL_RGB (according to pixel depth), and pixelData is the array of pixels. I verified that pixelFormat and pixelData and width and height have within them the correct values. Note that pixelData is a std::vector.

I bind the texture as such:

    glActiveTexture(GL_TEXTURE0 + this->multiTexNumber);
    glBindTexture(GL_TEXTURE_2D, this->texID);

For the purposes of my testing, this->multiTexNumber = 0;

Have I done something wrong here? Is the problem elsewhere?

EDIT: via very thorough checking, I have ensured that OpenGL doesn't throw any errors. The problem persists.


texts:
I am writing a game engine in C++, or rather, a framework of reusable classes. So far, I have created low-level wrappers for OpenGL constructs. For example, a VBO class, a VAO class, and a texture class. I figure it would be a better idea to design my engine/framework to be agnostic of the API backends used below - so basically, make higher-level classes like Texture and Mesh, which are then implemented differently depending on if you use OpenGL or Direct3D.

The problem I'm having is that I can't quite figure out a good way to do this. How would I structure my classes? How high-level is enough?

I'm aware that OGRE3D uses the above mentioned approach, but I find the way Ogre does this to be confusing, to say the least. Can anybody provide me with good information on how to create an API agnostic game framework, or at least briefly explain how Ogre does it?


texts: XNA GUI: Creating a 'scroll pane' widget

texts:
I'm trying to create a simple GUI system and am currently stuck on how to implement a textarea with a scrollbar. In other words, the text is too large to fit into the view area. I want to learn how to do this, so I'd rather not use an already rolled API.

I believe this could be done if the text were part of a texture, but if the game had a lot of unique dialog, this seems expensive.

I researched creating a texture on the fly and writing to it, but came up with nothing.

Any suggested strategies would be appreciated. I believe it boils down to: text in a texture and how? Or something I have not thought of...


texts:
I am a beginner in OpenGL. I am learning about textures in OpenGL. What I don't understand is how to determine how many texture units are in the GPU. I heard someone said that you can see how many texture units by writing the following code.
int total_units;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &total_units);
std::cout << total_units << '\n';  // the result is 192

Is there 192 texture units in my GPU?  In documentation, it says:

GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
params returns one value, the maximum supported texture image units that can be used to access texture maps from the vertex shader and the fragment processor combined. If both the vertex shader and the fragment processing stage access the same texture image unit, then that counts as using two texture image units against this limit. The value must be at least 48. See glActiveTexture.

So I wanted to know how many texture units can be used to access texture maps from the vertex and fragment shaders. So I wrote and run the following code.
int vertex_units, fragment_units;
glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vertex_units);
std::cout << vertex_units << "\n";   // the result is 32
glGetInteferv(GL_MAX_TEXTURE_IMAGE_UNITS, &fragment_units);
std::cout << fragment_units << "\n"; // the result is also 32

So 32+32=64. But why does GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS shows me the result of 192? I think I am missing something. What do I need to calculate to get 192?
And also, in OpenGL, why are there only GL_TEXTURE0 to GL_TEXTURE31 macros? I think these macros are for each shaders. Am I right?


texts: Are huge, static objects like environment transmitted from server to client in modern multiplayer games?

texts:
I have an authoritative system, where when the player joins the match, it gets all the already spawned objects - spawned on itself (the client).

It looks like this:

Client sends the access token to the Server
Client receives the acceptance from the Server
Client switches scene to the game scene
Server sends players, crates, objects you can interact with so the client can spawn and display them.

But what about the ground object?
For now, I have the exact same scene on the server and the client - with one static plane acting as a floor. Currently I'm adding new stuff, trees, stairs and build things together.

I thought - we're good. But shouldn't the environment be synchronized too? Be networked somehow? Owned by the server?

Let's take League of Legends:

It's a static environment, probably one combined mesh (stairs, grass, walls, shop). But is it really kept on the client or is it sent by the server during the loading screen?


texts: (Phaser) Preload Future States in Create?

texts:
I'm a first time user of Phaser, been trying to make a simple point and click type game. I'm trying to keep things very modular, so I'm defining a list of levels (states) in a JSON, and then every level has its own JSON containing the objects within that level.

However, I'm encountering an issue in that, when changing states, I get a black flash while the assets for the next state load (this happens whether I iterate through the JSON list or define everything manually). From what I've read, all sprites should be loaded in the preload stage, however, by doing this I'm causing that tiny but noticeable black pause.

I know one way would be to simply load every asset at the start of the game, but that seems incredibly inefficient (wouldn't that fill up the memory immensely?). I would rather load a state's assets from the "parent" state. However, in my quick test (which maybe I did wrong) it seems that game.load doesn't work properly if done within the create stage? What is the best approach to doing this?


texts: Can ANGLE OpenGL ES 2.0 use the same color / depth surface as Direct3D11?

texts:
Lets just assume I have some simple OpenGL ES 2.0 code that renders a box with depth writing / testing.  Is it possible to put this box in a middle of a Direct3D11 scene using angle?

The MS angle page https://github.com/Microsoft/angle/wiki/Interop-with-other-DirectX-code says that we can render to a texture, and I have tried that and it works fine.  But this only allows for 2D integration, not 3D integration, as far as I can tell.  I render my OpenGLES content to a texture (in 2d or 3d), but now I can only put a texture in the DirectX scene.  How can I have my OpenGL ES code write / read from the same depth/color surface that the DirectX11 portion is using?


texts: What revenue models can I use for a non-commercial game

texts:
I don't have any budget to buy commercial licenses but the libraries I use offer non-commercial free licenses.

How far can I go in regard to monetizing my game without it being considered commercial ? Donations? Do ads count? Optional items purchase?

For example, fmod states in their free license:

  This license cannot be used for commercial services, where the executable containing fmod is not sold, but the data is.

What if only some data (optional) is sold?

Thank you.


texts: Specular Light not working Phong shading

texts:
I want to implement Phong-Shading using GLSL. I also want to calulate all values using uniforms in the shaders.

Nearly everything works fine, but there is an error with the specular term of the equation.

Here is my vertex shader:

#version 330
layout(location = 0) in vec3 vertex;
layout(location = 1) in vec3 vertex_normal;

uniform vec3 light_ambient_color;
uniform vec3 light_diffuse_color;
uniform vec3 light_specular_color;
uniform vec3 light_position;

uniform vec3 material_ambient_color;
uniform vec3 material_diffuse_color;
uniform vec3 material_specular_color;
uniform float material_specular_shininess;

out vec3 vNormal;
out vec3 camVec;
out vec3 lightVec;

out vec3 diffuse;
out vec3 ambient;
out vec3 specular;
out float shininess;

uniform mat4 view;
uniform mat4 modelview;
uniform mat4 projection;

void main() {

    diffuse = material_diffuse_color.rgb * light_diffuse_color.rgb;
    ambient = material_ambient_color.rgb * light_ambient_color.rgb;
    specular = material_specular_color.rgb * light_specular_color.rgb;
    shininess = material_specular_shininess;

    mat4 normalMat = transpose(inverse(modelview));

    vNormal = vec3(normalMat * vec4(vertex_normal,0.0));
    vec4 pos = projection  * modelview  * vec4(vertex,1.0);

    camVec = pos.xyz;
    lightVec = (1) *(light_position.xyz - pos.xyz);

    gl_Position = pos;
}

And this is my fragment shader:

#version 330

in vec3 vNormal;
in vec3 camVec;
in vec3 lightVec;

in vec3 diffuse;
in vec3 ambient;
in vec3 specular;
in float shininess;

// this defines the fragment output
out vec4 color;

void main() {

  vec3 normal = normalize(vNormal);
  vec3 viewDir = normalize(camVec);
  vec3 lightDir = normalize(lightVec);

  vec3 myDiffuse = normalize(diffuse);
  vec3 myAmbient = normalize(ambient);
  vec3 mySpecular = normalize(specular);

    vec3 finalColor = ambient;
    float lambert = dot(normal,lightDir);
    vec3 specColor;

    if(lambert < 0.0){
        specColor = vec3(0.0,0.0,0.0);
    }else{
        finalColor += myDiffuse * lambert;

        vec3 h = (viewDir + lightDir ) / length(viewDir + lightDir);
        float beta = dot(h, normal);

        finalColor += mySpecular * pow(beta, shininess);
    }

    color = vec4(finalColor,0);
}

All uniforms are set correctly.
Here is what it looks like without the specular term:

And this happens when I add the specular term (which is not working):

Edit:
Another screenshot with changing pos.xyz to -pos.xyz in the vertex-shader


texts:
I'm working for collision response for my 2d game. Character is represented by circle and obstacles are represented by Polygons(in my example it would be rotated rectangle for simlification). The problem is when circle collides with vertice of polygon, I know how it must work , but can't find the vector.
C - the center of the circle.
V - vertice.
P - the center of the polygon.
X - the vector I need to find.

Then I'll just move my character by vector V.sub(X).
Tried this algorithm, but it gained no result.
https://stackoverflow.com/questions/1073336/circle-line-segment-collision-detection-algorithm


texts:
In all Unity games I saw so far, every object is either 2D (with RigidBody2D and Collider2D components), or 3D (with RigidBody and Collider components). This makes sense, but I wonder if there is any use to an object that has both (for example, both RigidBody2D and RigidBody, or both Collider2D and Collider)?

Are the worlds of 2D and 3D completely parallel and unrelated, or can they be connected somehow?


texts: Check if rectangle sides overlap each other in 2d

texts:
I am drawing a rectangle. On touching the corners, I am able to resize this rectangle. Now, the issue is during resizing, opposite sides overlap and cross each other. I have to stop this overlapping and crossing of sides. The minimum width and height should be any fixed constant (let's say 10).

In below code left, top has cornerId 0 and left, bottom has cornerId 1 and so on.
Also left, top and right, bottom makes groupId 1 and other two sides make groupId 2. Here cornerList contains the info about all the 4 coordinates.

Any help or reference is greatly appreciated. Thanks.

Reference for resizable rectangle is How to create a resizable rectangle with user touch events on Android?

private void moveCorners(float x, float y) {

    cornerList.get(cornerId).setX(x);
    cornerList.get(cornerId).setY(y);
    paint.setColor(Color.CYAN);

    if (groupId == 1) {
        cornerList.get(1).setX(cornerList.get(0).getX());
        cornerList.get(1).setY(cornerList.get(2).getY());
        cornerList.get(3).setX(cornerList.get(2).getX());
        cornerList.get(3).setY(cornerList.get(0).getY());
    } else {
        cornerList.get(0).setX(cornerList.get(1).getX());
        cornerList.get(0).setY(cornerList.get(3).getY());
        cornerList.get(2).setX(cornerList.get(3).getX());
        cornerList.get(2).setY(cornerList.get(1).getY());
    }

    invalidate();

}


texts: Version control with game development - When should I branch?

texts:
I recently started using Version Control with my projects (even though I'm working alone on them). I find that it gives a nice way to keep history of the whole development process (with issue tracking) and allows me to keep backups for my projects along the way.

As I slowly discover the features and advantages of using version control, I am stuck around the idea of branching. When should I do it?

Should it be every single time I go and develop a new feature, or only once in a while when I reach a certain milestone?

Obviously, branching is pretty useless when working alone, but I'd rather pick up good habits now and get used to it.

As I was reading the book Game Coding Complete by Mike McShaffry (which is a great book by the way), I got totally lost when the author recommended keeping three branches, something along the lines of:

Main: Main development branch where regular changes are made.
Gold: Gold branch where the last milestone reached is kept.
Research: Branch for testing stuff that could badly impact the Main branch (modifying important components of the game engine, etc.).

Is that how it is supposed to be? How does it really work in the world of game development with big teams of developers?

Basically: When does one usually branch (and merge) in game development?


texts:
I'm trying to make a game, but I'm not sure of the best way to set up the main loop and classes. For really small games, I could put everything in the main() loop, including event handling, collision checking, etc. However, for large games, that's seems like a highly inefficient way to get things done. The architecture I want is kind like the way the Minecraft coders did it (I quote Minecraft code because I've seen the source code when downloading MCP).

They have objects entity classes EntityCow and EntityChicken and they have methods like onDeath(), onLivingUpdate(); and item classes like ItemSword have methods like onItemUse(). I've never seen these methods get called directly, but apparently, they get stored in a class called DataWatcher, which, I think "watches" all the data (as the name implies) and calls the appropriate methods in the objects.

Is that how most games do it? If so, how is the DataWatcher class implemented? Any help or alternate suggestions is really appreciated.


texts:
I'm currently using a Raycast both for my movement check aswell as a focus-setting check, both checks use pretty much the same code.
The problem i'm having is that the Raycast goes through some objects and targets the background no matter what i've tried to far. As you can see in this screenshot, I first clicked on the black sphere (Just a 3D Sphere in my 2D world with a default Sphere Collider) and the Log shows so aswell, however when i click on the white box which the second Debug Log is supposed to be, it just ignores the box collider and goes straight to the Background (the green sprite). The same problem with the Interactable check, code works completely fine with the Sphere but not with the box. Here's the Code i currently use:

    //Movement
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100))
        {
            Debug.Log("We hit " + hit.collider.name + " " + hit.point);
            RemoveFocus();
            targetPosition = hit.point;
        }
    }
    if(targetPosition != (Vector2)transform.position)
        transform.position = Vector3.MoveTowards(transform.position, targetPosition, maxSpeed * Time.deltaTime);

    //Check for Interactable, pretty much same code...
    if (Input.GetKeyDown(KeyCode.Mouse1))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 200))
        {
            Interactable interactable = hit.collider.GetComponent<Interactable>();
            if(interactable != null)
            {
                SetFocus(interactable);
            }
        }
    }


texts:
I am using BodyA.getPosition().x and BodyA.getPosition().y to get the x and y vector of a body location so i may attach some text above its head, but the log of that position prints out something like 3.666757..... I want this text to be moving when the body moves so it should be relative to the body position at all times until removed. Currently when I try to use this

speech = new TickerText( 0, 0, font,
            ptext, new TickerText.TickerTextOptions( 10 ),
            ResourceManager.getInstance().vertexManager );

speech.setBlendFunction( GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA );
speech.setScale( 0.5f );
speech.setAutoWrapWidth( 500f );
speech.setAutoWrap( AutoWrap.WORDS );
speech.setPosition( xVal, yVal );`

The text is not displayed on screen on screen at all, I figure its the x and y location being wrong because when I manually set x and y to positions I know would be on the screen area it is shown. I am looking for help as how to get the actual X and Y coordinate of the body on screen so I can have the text follow the body.


texts: Unity Multiplayer functionalities or Google's plug-in?

texts: I want to add multiplayer matches to a game I'm making for Android/PC, and something echoed in my mind: would the network functionalities Unity provides work in Android? I ask this because Google has a free plug-in for their services, but Unity also offers possibilities. Also, using any of the above, do I need to pay to rent a server? Or, for example, since we need a paid developer account to register our game at Google Play Store, the servers are part of the deal?


texts: How to do collision detection in Unity between Character Controller, Rigidbody Collider and a NavmeshAgent?

texts:
I would like to know more about how collision detection works in Unity especially when character controllers and NavmeshAgents get involved.

For example, how can I detect collision between NavmeshAgent and a CharacterController?
I have added a sphere collider to my NavmeshAgent, but it doesn't seem to detect a collision unless I set it to "IsTrigger".
I have tried OnCollisionEnter(), OnControllerColliderHit() and OnTriggerEnter().
OnTriggerEnter() seems to be the only one that works and only when I enable "IsTrigger".

How come the other two don't work? Shouldn't they? What if I didn't want to make the collider a trigger?


texts: What can I use to generate 2d vector graphics as a list of coordinates?

texts:
I am working on a game that uses simple 2d vector graphics. I want a tool that will let me visually draw things like arbitrary polygons by placing points.

A perfect tool would present a grid that I could scale larger or smaller (ie: the window is 10 units across or the window is 20 units across). It would let me draw a polygon on this grid, and will tell me, simply, the coordinates of each point.

It would be great if this tool could then export a file format that was something like

0, 5
3, -2
0, 0
-3, -2

For bonus points, it would be great to be able to assign other attributes to each point. In the end, this will get passed to OpenGL, so things like color and opacity could possibly be used.


texts: Is there a more general property or class of properties or concept that encompasses position and space?

texts:
Is there a more general property or class of properties or concept that encompasses the concept of position and space?

It does not seem clear to me that position is the most general property (if it is a property) applicable to an object, so I have been searching for a more general property, or class of properties, which will include the property of position, but I have been unable to find anything.


texts: How to predict movement correctly when a player is invisible?

texts:
I have a multiplayer game and I'm doing client-side prediction, but some players can drink a potion and become invisible...

The problem is that when they become invisible I don't share anything that the client could use to know he's there, so when a player tries to step into a tile occupied by a invisible player, he predicts that he succeeds, and then gets a ugly position correction sent by the server.

One solution would be to share something so the client can tell, but then hackers could use it to find out where invisible players are, cheating.

Btw I already solved regular movement prediction, it works perfectly.


texts: Linear interpolation: reach moving destination regardless its speed

texts:
I'm implementing a camera for a game and I'm using the LERP formula for smooth chasing. However, if the target moves fast enough, the camera can never reach it unless the t ((1 - t) * v0 + t * v1) value is high enough, but that is exactly the problem: some targets might still move faster than the current t value.
This might lead to 2 problems:

The camera will never reach the object if it's super fast
The camera will very slowly reach the object, depending on its
current speed

How do I scale up my t when the delta distance (abs(v1 - v0)) gets lower, so that the camera will starts at a slow chasing rate and increases as it gets closer (therefore no targets could run away)?


texts:
In Box2D, I was curious if it's possible to get a bounding box of a body already created in the world.

So basically, the Body is created, it's interacting with the world and such. And I needed that Body's bounding box. Is it possible?


texts: What do I need to consider before making any class singleton?

texts: I am sure most of my classes like for rendering text, sprite, shapes are not going to need more than one instance. Is it adequate to consider only this fact that its only going to need one instance? Should i also consider other things?


texts: Please help me with my 2D isometric tile picking

texts:
Possible Duplicate:
  How to convert mouse coordinates to isometric indexes?

Okay, I apologise in advance if I make no sense here.

Basically, I've got a simple application that takes in a file and populates a 2D array with tile objects that contain the type of tile, their X and Y values, location of the sprite in a tile map etc. The application then renders this back to front so the depth is sorted. The camera can be dragged about.

for (int i = 0; i < map.length; i++){
        for(int j = 0; j < map[i].length; j++){
            m_MapTest[i][j] = new Tile(((j * Tile.TILE_W / 2) + (i * Tile.TILE_W / 2)),
                      ((i * Tile.TILE_H / 2) - (j * Tile.TILE_H / 2)),
                      map[i][j], 0, map[i][j], 0);

The output:

The numbers are an example of where these tiles are located in the array. Ignore the temporary art.

How do I get the tile index of my mouse click? I've tried about 10 different picking algorithms including matrix translations but I haven't got anywhere. The closest I got was the application picking the right tile in one direction, yet the other axis would start at negative one, the next tile would be zero, the next would be zero then the next would be one and would be correct from there, although I seem to have deleted this in frustration. I feel bad that I don't really have any code for this.

My tile width is 64 and the height is 32, although the sprites are 64x64 and the actual tiles are located at the bottom of the image, if that makes sense... I have done it like this as I am planning on having varied tile heights.

If you need any more information to help me, please let me know. Math is not my strong point.


texts:
Been digging through the animation tools in Unreal, trying to find a direct way to set keyframes and edit animation curves on a skeletal mesh. It seems far more complicated than I expected, generally requiring imported poses and animation that is then edited, mixed, etc... in blueprints.

What I am wondering, is there an efficient way to

take a skeleton,
position and keyframe its bones in one place not with multiple bone transform nodes wired together
then edit the resulting animation curves

so as to set poses and create animation directly in the editor, or is the only reasonable way to keyframe and edit curves when using Unreal is in an external program?

If it is practical, what editor panes, blueprint nodes, and game objects would I use?


texts: Advice for a table top rpg with rpg systems

texts:
English isn't my first language so sorry in advanced for odd wording.

Idk if this is the right type of form but,I would like to make a game much Like D&D.
With that said basic attacks seem to work out just fine no matter lvl or stats I think that the numbers come out a fair.

mag= (100 + buffs + gear) = sum
res= (100 + res + buffs + gear) = sum
magic damage =(A.mag*mag.sum)/(res.sum)

This pushes out fairly low numbers that are then ran into a set of code that does the damage by number of its.

*1 for attacks that are 5 to 10 hits
*2 for 2 to 4 hits
*4 for single hit skills and spells. (had a problem that made single hits to weak for a time.)
*.5 for skills/spells that hit 11 to 15 times.

So here is where the problem comes in this is a Ip i made over years of thinking and putting things together. Spells are ranked from 1 to 5 however 5 is a insta win at the cost of the users life.

I do want to note as Dm I use my pc to run the above code. I would love to hear any form of tips or advice that might make things run a little better in the long run.

If we plug the numbers from the race above at level 1 those numbers being 40 magic and give the attacker a weapon buff of 20 and a attack buff of 10 it should come out to 130. Note that the magic attack will not be used in getting the sum of these buffs. Now lets make the defends gear a gear buff of 10 and a res buff of 15. the res stat is used in the code as shown below leading us to our sum of .155

attacker (100 + 20 + 10) =130
defender (100 + 30 + 10 + 15) = 155

These numbers would give us our sum. this is then plugged into another set of code as seen below

(Mag*attacker sum)/(defender sum)

so if we plug in the numbers it should look like this.

(40*130)/(155)= 33.54

This is then taken automatically by the system and * by the following numbers 2,4,.5 this displays the outcomes of the above number as the first hit in the combo.

(40*130)/(155)= 33.54 <this is then * by the number of hits a 5-10 hit>
(40*130)/(155)= 33.54*2 = 67 <*2-4>
(40*130)/(155)= 33.54*4 = 134 <single hit spells>
(40*130)/(155)= 33.54*.5 = 16 <*10 to 15>

So to explain the above numbers lets say I use a spell that cast 15 chances to hit in damage that spell would use the formula of 10 to 15 or .5 making each hit deal 16 damage if they all land that would be 240 damage taken. if unlucky however only 3 of those 15 could hit and you would still use the 16 as your base damage for said attack.

In theory this should be fine (i think) this makes some AoE's broken as a AoE without a chance to miss would deal massive damage every time. So maybe in the long run my question might really is their a way to make this more fair for pvp?

In case asked

Yes I am likely tying harder than I need to.

I can also Show what a a good player sheet and a broken player sheet look like if someone thinks it would help. I do hope that this is more clear than before or at most gives a better idea of what i'm tying to ask.

I have never made a game I have less than a year of html,c# and,c++ under my belt so i hope it kinda looks like it should work.

Thank you for all replies


texts:
I'm stumped.  I have been fighting this for about 2 hours now.

Here are the interesting parts of my code:

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    var time = gameTime.TotalGameTime.TotalSeconds;
    this.position = new Vector3(
        2.0f * (float)Math.Sin(time),
        2.0f * (float)Math.Cos(time),
        2.0f * (float)Math.Cos(time / 4));

    effect.World = Matrix.Identity;
    effect.View = Matrix.CreateLookAt(this.position, Vector3.Zero, Up);
    effect.Projection = Matrix.CreatePerspectiveFieldOfView(1.5708f, (float)this.Window.ClientBounds.Width / this.Window.ClientBounds.Height, float.Epsilon, 500.0f);

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    var count = this.SetUpVertices() / 3;

    this.GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.CornflowerBlue, 1.0f, 0);

    this.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
    this.GraphicsDevice.BlendState = BlendState.Opaque;
    this.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

    foreach (var pass in this.effect.CurrentTechnique.Passes)
    {
        pass.Apply();
        this.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, count, VertexPositionTexture.VertexDeclaration);
    }

    base.Draw(gameTime);
}


texts: I want to rotate all my GameObjects by 90 degrees. To do that I need to select all my GameObjects, how can I do so?


texts:
I have a revolute joint set up as such in libgdx + box2d:

            RevoluteJointDef rjd = new RevoluteJointDef();
        rjd.initialize(body1, body2, arm.getWorldCenter());
        rjd.motorSpeed = 100.0f;
        rjd.enableLimit = false;
        rjd.enableMotor = true;
        rjd.collideConnected = false;
        world.createJoint(rjd);

The joint displays and connects fine, but it never seems to turn or rotate. After some googling some people said to increase the motor speed, but I've turned that up to ridiculous values with still no rotations. The density of both body1 & body2 are set to 1.0f, so I'm not sure what else to do (both bodies are dynamic).


texts: Overriding the sprites in a Animation clip

texts:
Right now we are in the process of adding seasonal content to our game. I would like to know of a way to override animation clips. Specifically I want to change the sprites being show at each key-frame. Looking from the text of a animation clip I found the following :

 m_PPtrCurves:
  - curve:
    - time: 0
      value: {fileID: 21300000, guid: 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type: 3}
    - time: 0.6
      value: {fileID: 21300000, guid: ae9111d826eb24442b21523b30b748bd, type: 3}
    - time: 0.6666667
      value: {fileID: 21300000, guid: 88840e4f59c4a6040922d9b6eed3dec3, type: 3}
    - time: 1.2333333
      value: {fileID: 21300000, guid: 88840e4f59c4a6040922d9b6eed3dec3, type: 3}
    - time: 2.0001667
      value: {fileID: 21300000, guid: ae9111d826eb24442b21523b30b748bd, type: 3}
    - time: 2.05
      value: {fileID: 21300000, guid: 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type: 3}
    - time: 3.1166666
      value: {fileID: 21300000, guid: 502fc97a961e4424ea008c0e546c83ef, type: 3}
    - time: 3.45
      value: {fileID: 21300000, guid: 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type: 3}
    attribute: m_Sprite

This corresponds to the key frames and amount of sprites in the animation clip but I have no idea from where to get the data for the new sprites. I'm guessing the guid is a hashed path to the png files. can someone  explain where to find this data so I can write myself a neat little parser to do the job?


texts: Smooth Sprite Movement - Don't Add Velocity to Position?

texts:
I am trying to figure out if there is a way to move a sprite smoothly on the screen at different speeds without stuttering, but keeping the effect that it's moving smoothly; especially at faster velocities.

Below is a basic version of what I have with all of the object specific logic stripped out for readability.

void MoveableGameObject::update(double time)
{
    //maxVelocity is 10
    currentVelocity = min<float>(currentVelocity + acceleration * time, maxVelocity);
    location.x += currentVelocity;
}

void MoveableGameObject::draw()
{
    sprite->draw(location.x, location.y)
}

The part that I do not like is that the next time the frame renders and max velocity has been achieved, the sprite jumps 10 pixels and looks stuttery. If I tone down the numbers then it is of course smoother, but also slower.

I need to find a way to still have the speed, but give a smooth transition somehow. I am having a hard time wrapping my head around trying to implement movement speeds. Am I just using the wrong scale in terms of velocity to pixels?

My brain hurts, but I am still having a blast tinkering around with this and is a nice change of pace from doing nothing but business applications for the past 7 years.

I do have the ability to say run the game logic 20 times a second while rendering at 60 frames a second. Figured I would mention that in case that helps with an answer. Currently they are both just set to 60 since I am only running a single sprite and wanted to test the movement and check the sprite location on update() vs. draw().

Thanks in advance for any help.

EDIT: I forgot to mention and not sure if it matters or not, but I am currently using SDL to render.


texts: Any reliable polygon normal calculation code?

texts:
Do you have any reliable 3d polygonal face normal calculation code?

Any language will do, I'll port it to make it work. Even if you find some code in a 3d game engine and post it here I'll be more than grateful.

Edit:

I'm using this but it fails when faces are 90 degrees upright or similar.

        // the normal point
        var x:Number = 0;
        var y:Number = 0;
        var z:Number = 0;

        // if is a triangle with 3 points
        if (points.length == 3) {

            // read vertices of triangle
            var Ax:Number, Bx:Number, Cx:Number;
            var Ay:Number, By:Number, Cy:Number;
            var Az:Number, Bz:Number, Cz:Number;
            Ax = points[0].x;   Bx = points[1].x;   Cx = points[2].x;
            Ay = points[0].y;   By = points[1].y;   Cy = points[2].y;
            Az = points[0].z;   Bz = points[1].z;   Cz = points[2].z;

            // calculate normal of a triangle
            x = (By - Ay) * (Cz - Az) - (Bz - Az) * (Cy - Ay);
            y = (Bz - Az) * (Cx - Ax) - (Bx - Ax) * (Cz - Az);
            z = (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax);

        // if is a polygon with 4+ points
        }else if (points.length > 3){

            // calculate normal of a polygon using all points
            var n:int = points.length;
            x = 0;
            y = 0;
            z = 0

            // ensure all points above 0
            var minx:Number = 0, miny:Number = 0, minz:Number = 0;
            for (var p:int = 0, pl:int = points.length; p < pl; p++) {
                var po:_Point3D = points[p] = points[p].clone();
                if (po.x < minx) {  minx = po.x;     }
                if (po.y < miny) {  miny = po.y;     }
                if (po.z < minz) {  minz = po.z;     }
            }
            if (minx > 0 || miny > 0 || minz > 0){
                for (p = 0; p < pl; p++) {
                    po = points[p];
                    po.x -= minx;
                    po.y -= miny;
                    po.z -= minz;
                }
            }

            var cur:int = 1, prev:int = 0, next:int = 2;
            for (var i:int = 1; i <= n; i++) {

                // using Newell method
                x += points[cur].y * (points[next].z - points[prev].z);
                y += points[cur].z * (points[next].x - points[prev].x);
                z += points[cur].x * (points[next].y - points[prev].y);
                cur = (cur+1) % n;
                next = (next+1) % n;
                prev = (prev+1) % n;
            }
        }

        // length of the normal
        var length:Number = Math.sqrt(x * x + y * y + z * z);

        // if area is 0
        if (length == 0) {
            return null;

        }else{
            // turn large values into a unit vector
            x = x / length;
            y = y / length;
            z = z / length;
        }

Edit:

I can somehow display 3d arrows for each calculated normal and go so far as to document test cases where it worked and failed. But I was looking for a simpler solution, simply by using code that someone else has created and found to be working. Is OpenGL all you have? Doesn't anyone have any triangle/polygonal normal calculation code at all?

To Jari:

I'm using this code to calculate normals, as built from OpenGL's pseudo code. Is there something I've done wrong? and what would happen if the points are not perfectly inplane? would it fail and return a random normal or just change the normal slightly?

            n = points.length;
            x = y = z = 0;
            for (i = 0; i < n; i++) {
                j = (i + 1) % n;
                x += (points[i].y - points[j].y) * (points[i].z + points[j].z);
                y += (points[i].z - points[j].z) * (points[i].x + points[j].x);
                z += (points[i].x - points[j].x) * (points[i].y + points[j].y);
            }


texts:
Ok, so the title isn't the greatest because this is a lot more general.
Say I want to have the player be able to hit A and have their ship model roll to the right, and shift to the right of the screen, while the camera stays centered. Would I do that through programming (ie. set waypoints for the model and keep the camera focus still) or do it through animation ( so the ship model actually rolls and moves right, and just play those frames)(I actually don't know how to do this kind of 3D animation yet, haven't looked into it. Adding it to my To Do List)

This is a really vague question I know, I'll try and answer any questions.

Thanks,
Peter


texts: Special character's with LibGDX's I18NBundle such as "ü" or "ö" are marked as unknown

texts:
I am loading my I18NBundle like this :

    assetManager.load("i18n/language", I18NBundle.class);
    assetManager.finishLoading();
    i18NBundle = assetManager.get("i18n/language", I18NBundle.class);

When I get(String key) the values of the german localization I get these symbols for the ü and ö characters. This is what it looks like when I use the debugger to see the mapped values :

In-game, it will display Huser instead of Häuser.

The french localization works fine with é and è. So I'm quite confused as why only the german localization fails.


texts:
Is there any sophisticated game AI engine that can save time on AI implimentation and provides strong and clever AI? The game genre is strategy, so AI should be strong. The game in some aspects is similar to the starcraft. So we can use it as good example. As for me SC2 game AI is is very weak. When I played it, I quickly found very simple strategy line with help of it which could win in 100% of cases for any race. After that it was not interesting to play. So I want stronger AI, and AI that can learn. I don't like deterministic algorithms.  I can accept some good end state machine algorithm, but good implimentation of such algos requare long time and testing. And all of such algos in stratgies are week and not interesting once the player has found weaknesses.

I can try to impliment AI by myself using neural networks, genetic algo or something like that.. but that will requare even more time.

So I am interesting in some ready sophisticated game engine, that would be easy to train and adjust under myself. I looked and found only http://alive.sourceforge.net/ ... it not looks very populat, fast and sophisticated.

(The game is openGL/C++. I have enaph free processor resources for AI)


texts: Determine facing direction from camera vector/yaw

texts:
I'm trying to determine the cardinal direction (west/north/east/south) that a player (camera) is facing. I have a 3d world setup with a camera that properly moves in any direction and I have the yaw/pitch and obviously the currently coordinates of the camera.

I've found several examples that determine another coordinate in the current direction but I only want the current direction - in radians most likely, then I can use that to determine a cardinal direction.


texts: Displaying a particular sprite from spritesheet using Phaser

texts:
I am trying to make a card game using Phaser, the HTML5 JS framework.  Because I'm a terrible artist and can't design my own, I'm using a free spritesheet of playing card images I found online.  The problem is, I can't seem to figure out how to display individual cards using Phaser.

In the previous framework I used, I was able to create individual smaller sprites from the larger sprite sheet that I used.  But I can't figure out how to do that in Phaser, if it's possible at all.

So I looked into loading the image as a spritesheet, but it seems that spritesheets are used for animation only and you can't really display a particular 'frame' of the spritesheet (please correct me if I'm wrong).

I think what I need to do is load the image as a tilemap, however, the particular image that I'm using did not come with a json file specifying the layout (nor could I find one that did).  Being new to javascript I'm having trouble reading the Phaser source code to see how the json file should be formatted.

So in summary, what's the best way to display an individual card of a spritesheet of playing cards in Phaser given that I don't have a json file specifying the map data?


texts: How to implement multicolored flashing sprite effect like in Contra and the Messenger?

texts:
I want to implement an effect similar to what you see in this clip of Contra.

When the boss takes damage, he flashes wildly with different colors.

A similar effect can be seen in this clip from the Messenger (with the addition of an outline).

I don't care how they did it in Contra or the Messenger. I want to achieve a similar effect, preferably with a shader using GLSL.

Any ideas on how to go about it?

The effect seems to alternate the sprites between red and blue palettes, but I'm not sure if palette swapping is an effective way to achieve this, especially since I don't have my art assets in gray scale.

Maybe a hue shift shader is a viable alternative? Or maybe there's another way.


texts:
I have recently been toying with the idea of creating a 3D-renderer from scratch and, after looking into it, doesn't seem like such a behemoth of a task as it sounds. Last night, I was tossing and turning in bed because I had tons of ideas and was originally going to base the whole entire renderer off of an index system using vector-lists it occlude points that I don't need, but tossed that out of the window as I realised I needed to prioritise on the main rendering.
As most 3D-based developers will know, all of the vertices move around the viewport. This is a nightmare for people who want to make 3rd/1st person games because, if you don't know semi-advanced geometry then you're practically screwed. I realise that people will have to know about their soh's and their toa's eventually but I wanted to release the burden of that by having the viewport (matrix) move around the "world".
This is surely better for performance as well, as moving a matrix around must be easier for a gpu/cpu to calculate. I could be totally wrong, but I wanted to give this a go.

In my head, everything sort of works and would produce a "3D" world.
The only thing stopping me jumping into C++ and SFML/SDL at this point is a bug (or technically "unimplemented feature") of my program. The way I was going to have my renderer work is like so:

Find all vertices inside of viewport. (Lets call these V[] )
Get depth information of all V[]
Draw lines between certain V[] (In my case, one V will contain information such as, the next V in memory to connect to. Drawing lines is only for debug purposes or for the kewl 80's look.)
Save as a polygon.
Fill colour/texture within a poly's bounds to show depth or for design.

This should work, I think. But there is one issue and that issue is the reason I'm posting all of this.

Let's say that we have something that is bigger/not completely in a view frustum bounds and the camera is not looking at a vertex, how would we figure out that there is a "shape" there. I'm going to draw a crappy example in MS Paint to explain. (Ain't nobody got time for Photoshop..)

Any help is appreciated and a fully understand if what I wrote doesn't 'click'.
Thanks!


texts: LWJGL Resize window and glTranslate breaking screen resolution

texts:
I'm trying to make a 2D Tile RPG game with LWJGL but I'm having a problem with the display resizing. I want the user to be able to re-size the window to whatever size they want just by expanding it (as opposed to letting them pick a resolution option from a list).

See the images below for the problem.

At default resolution:

At a re-sized resolution:

As you can see the tile is drawn correctly in the first image. However, after moving the camera and resizing the display the tile gets cut off as it moves away from the bottom-left corner of the screen.

The default screen-resolution is 800x600. I have a camera object that moves based on the player using the WASD keys. I decide what's to be drawn by using glTransaltef(camera.x,camera.y,0). Should I use if(Display.wasResized()) in the game loop then get what the new resolution is and use it in the glTranslatef function somehow? Any help or suggestions would be great!

EDIT: I added the code in Fletcher D's answer however it produced this:

The tile doesn't get cut off anymore but in the image above the tile is being drawn at a size of 1x1 pixels. Also when the screen resolution changes the resolution of everything on screen changes, this is not what I want. I want the screen to simply display more of the world. As I said I'm using a panning camera that moves with the player's WASD keys. So if the world is currently being displayed at 0,0 to 800,600 and the player re-sizes the window to 1080x720 I want the display to show the world from -140,-60 to 940,660. (Maintaining the center of the screen at the moment of being re-sized.


texts: Setting 4 different enemy spawn zones off screen

texts:
This is my first game, so I really appreciate all the help.

I want to create four enemy spawn zones for enemies and this areas are off screen. The enemies are coming from left, right, up and down, and their destination is a sprite on the center of the screen. And there are 4 types of enemies (only thing that changes is color).

Current code I have only makes the enemies come from the right direction into the screen. I don't really know the reason of this, I am really new to game making and some of this methods.

Relevant code I have for enemies if the following:

private void createEnemies() {
    listP.add(regionA);
    listP.add(regionV);
    listP.add(regionAm);
    listP.add(regionR);
    Random ran = new Random();
    int z = ran.nextInt(3 - 0 + 1) + 0;
    Sprite ship = loadSprite(100, 100, listP.get(z));
    attachChild(ship);
    Enemies enemy = new Enemies(ship);

}

 @Override
protected void onManagedUpdate(float pSecondsElapsed)   {
    listP.add(regionA);
    listP.add(regionV);
    listP.add(regionAm);
    listP.add(regionR);
    Random ran = new Random();
    int z = ran.nextInt(3 - 0 + 1) + 0;
    super.onManagedUpdate(pSecondsElapsed);
    timeEnemies +=  pSecondsElapsed;        //  Acumulates time
    if  (timeEnemies>TIME_LIMIT)    {   //  Time has completed
        timeEnemies =   0;
        Sprite spriteEnemy  =   loadsprite(GameControl.CAMARA_WIDTH+listP.get(z).getWidth(),
                (float)(Math.random()*GameControl.CAMARA_HEIGHT-listP.get(z).getHeight())   +
                        listP.get(z).getHeight(),listP.get(z));

        Enemigos newEnemy = new Enemies(spriteEnemy);
        //newEnemy.mover(0,10);
        listEnemies.add(newEenemy); //  Adds it to the scene
        attachChild(newEnemy.getEnemySprite()); //  adds to list

    }

    //  Updates enemies and checks if any has gone offscreen
    for (int    i=listEnemies.size()-1; i>=0;   i--)    {
        Enemies enemy   =   listEnemies.get(i);
        enemy.getEnemySprite().setPosition(GameControl.CAMARA_WIDTH,0); // <-- Was experimenting with this code, but doesn't really help now
        enemy.mover(-10,0);
        if  (enemy.getEnemySprite().getX()<-enemy.getEnemySprite().getWidth())  {
            detachChild(enemy.getEnemySprite());        //  Eliminates from scene
            listEnemies.remove(enemy);                                                                  //  Eliminates from the list
        }
        //  Checks collision with center sprite

        if  (spriteCenter.collidesWith(enemy.getEnemySprite())) {
            detachChild(enemy.getEmemySprite());

        }
    }
}

Enemies class:

public class Enemies {

private Sprite sprite;

public Enemies(Sprite sprite) {

    this.sprite = sprite;
}

public Sprite getEnemySprite() {
    return sprite;
}

public void setSprite(Sprite sprite) {
    this.sprite = sprite;
}

public void mover(int dx, int dy) {

    sprite.setPosition( sprite.getX()+dx, sprite.getY()+dy );
}

}


texts: IsoMetric Map draw: sort with Z-Buffer and anchor point

texts:
I'm writing an IsoMetric renderer for my html5 isometric game. The isometric renderer should be able to render objects with floating point coordinates.

SOURCE: https://github.com/ilmattodel93/EaselJs-Isometric-with-Heightmaps

As now, the renderer works pretty well, but I have some questions and a problem to fix.
Note that little square is the anchor point, and lines are AABB (not correctly drawn I think).

THE PROBLEM

If you have a look at the demo, you should note that when the dragon is behind the tree on a higher level, it will be rendered over the tree instead of behind, as expected.

As you can see in js/mmo/renderer/IsoEntity.js#L91 and js/mmo/renderer/IsoLayer.js#L65, i have a "rough" implementation, and maybe it is'nt good.
I've googoled around and find something called "topological sort", i've attempted to implement it, but it does'nt seems to solve.

For each tile I have information about minX, minY, minZ, maxX, maxY, maxZ. An AABB as you can notice.

THE QUESTION

My question is, how can I solve this problem? Is it better (and will be faster) to maybe implement a depth-buffer? And how can I implement it? Will it ensure high performance? Maybe will a correct anchor point (represented with little square) solve the problem?

Thanks for any help! :D


texts: OutOfBounds Exception when creating a PolygonShape using jbox2d

texts:
So here's the deal, i'm parsing a file that contains the vertices for a polygon, that i want to create in box2d. I create a new PolygonShape() and then call .set() giving it a defined array of Vec, and that defined array's .length property. I expected this to work, since the documentation for jbox2d says this method takes a Vec array, and the count of Vec objects in that array. However, it errors out, and it seems to be unrelated to my code. The error i get is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at org.jbox2d.collision.shapes.PolygonShape.set(PolygonShape.java:174) and, upon looking at that line in the jbox2d svn repository, i still cannot figure out the issue.

Any help is appreciated!


texts: Unity3D RigidBody adding force diagonally (x,y,0) results in two separate movements instead of one diagonal movement?

texts:
The intentions of this function are to utilize the RigidBody component from a "target" object and clear its force while applying a diagonal force in the direction upwards and away from the side they are facing. I have omitted the portion in which detects the other direction for the sake of simplicity in reading the function as I've been testing this function while the user faces the right-hand direction.
Variables:

target refers to the other object currently in the scene
targBody refers to the RigidBody component of the target
object   damage refers to the current damage integer of the
object.      The damage used in this instance is from the target
object   facingRight refers to a bool in which is true
whenever the current object is facing the right-hand
direction.

    public void Damage() {
        targBody.velocity = Vector3.zero;
        if(facingRight) {
            Vector3 newVel = new Vector3(target.GetComponent().damage/16, target.GetComponent().damage/16, 0);
            targBody.AddForce(newVel, ForceMode.Impulse);
            print("Stuff");
        }
        target.GetComponent().damage+=3;
    }
For some reason, when I apply the force, the target object doesn't move diagonally. Instead, it moves horizontally before moving vertically; however, for some strange reason the horizontal speed is always greater than the vertical speed as it goes so fast that it nearly teleports!
I'm not sure if this error happens because of a coding problem on my part that I'm just not recognizing or if it's a problem with RigidBody in which I need to use a workaround for.Anyone have any ideas on what can make this function work the way I want it to?


texts: I am writing a little game engine in LWJGL. I want to have a gravity, but I don't know correct equations. Let's assume that I've got a 3D vector marking gravity force in each axis(e.g. Vector3f(0.0, -9.8, 0.0) would be Earth's gravity), object's mass and object's CdA(coefficient of drag multiplied by approximated object area). I wanna know how to correctly calculate object's gravity!


texts: Getting BEPUphysics to draw its entities

texts:
Isn't there a way, to force BEPUphsyics to show what it is doing?
I am here with my existing XNA project, starting to put in BEPUphysics,
but I am not seeing what it is doing.

Take my model for instance. I think I made a StaticMesh here:

public BEPUphysics.Collidables.StaticMesh PhysicsMesh;
public Space space;
private Hero _hero;

public override void LoadContent()
{
   //...

   space = new Space();
   Vector3[] vertices;
   int[] indices;
   TriangleMesh.GetVerticesAndIndicesFromModel(_model.getCoreModel(), out vertices, out indices);
   PhysicsMesh = new BEPUphysics.Collidables.StaticMesh(vertices, indices, new AffineTransform(new Vector3(0, -40, 0)));

   space.Add(_hero.PhysicsMesh);
   space.ForceUpdater.Gravity = new Vector3(0, -9.81f, 0);
}

That's the only thing I made BEPU-Wise in my game. All other models don't have
physics attached to them.

But, like I said. I see nothing when the game is running. Only my model, not falling, not doing anything.

I would like to see the full thing BEPU is doing in runtime.


texts: LibGDX Box2dlights - Body Shadow Problem

texts:
While playing around with the box2dlights with libGDX, I have managed to get it all up and running, but have a problem with the shadow rendering.

This is what I currently have atm:

With the lighting on:

With the lighting off:

What I want is to have the shadow be rendered so that the body is visible when the light is shone upon it, so that the platform is visible.

Here's some of my code that I use to create and render my lighting:

    // world lighting creation
    rayHandler = new RayHandler(physicsWorld, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    rayHandler.setBlurNum(0);
    rayHandler.setBlur(false);
    rayHandler.setAmbientLight(.05f);

    // world lighting rendering
    rayHandler.setCombinedMatrix(cameraWorld.combined.scale(PIXELS_TO_METERS / SCALE_TO_SIZE, PIXELS_TO_METERS / SCALE_TO_SIZE, 0),
            cameraWorld.position.x / PIXELS_TO_METERS * SCALE_TO_SIZE, cameraWorld.position.y / PIXELS_TO_METERS * SCALE_TO_SIZE,
            cameraWorld.viewportWidth, cameraWorld.viewportHeight);
    rayHandler.updateAndRender();

    // player torch light creation
    torchLight = new ConeLight(rayHandler, 50, Color.WHITE, 50 / SCALE_TO_SIZE, x / SCALE_TO_SIZE, y / SCALE_TO_SIZE, angle, 35);
    torchLight.setStaticLight(false);
    torchLight.setSoft(false);

Any thoughts?


texts:
(i'm on OPENGL)

i have a mesh O (object) and a mesh T (terrain).
i know a single triangle in T and i want to orient O to be aligned to that triangle (torate O to align to T in that point).

i have only the normal in the triangle. how can i achive the roation matrix?

i have thought this algorithm:

// pseudocode
float[] normal2rotation(Vector3D normal) {
    angleX = Vector3D.angleBetween(normal, Vecto3D.Axis3D.X);
    angleY = Vector3D.angleBetween(normal, Vecto3D.Axis3D.Y);
    angleZ = Vector3D.angleBetween(normal, Vecto3D.Axis3D.Z);

    float[] result = {angleX, angleY, angleZ};
    return result
}

but it does not give me the desired result.


texts: Morph a sphere to a cube and a cube to a sphere with GLSL

texts:
I'm getting started with GLSL with quartz composer.
I have a patch with a particle system in which each particle is mapped into a sphere with a blend value. With blend=0 particles are in random positions, blend=1 particles are in the sphere. The code is here:

vec3 sphere(vec2 domain)
{
    vec3 range;
    range.x = radius * cos(domain.y) * sin(domain.x);
    range.y = radius * sin(domain.y) * sin(domain.x);
    range.z = radius * cos(domain.x);
    return range;
}

// in main:

vec2 p0 = gl_Vertex.xy * twopi;
vec3 normal = sphere(p0);;
vec3 r0 = radius * normal;
vec3 vertex = r0;

normal = normal * blend + gl_Normal * (1.0 - blend);
vertex = vertex * blend + gl_Vertex.xyz * (1.0 - blend);

I'd like the particle to be on a cube if blend=0

I've tried to find but I can't figure out some parametric equation for the cube.
Maybe it is not the right way?


texts:
I'm trying to make a 2D Graphic engine for training me. I've actually made it with immediate draw and I've made the renderer outside (so I can switch between OpenGL and DirectX).

How can I manage Vertex Buffer Object and Vertex Array Object? I've made a geometry object, and I don't think VBO and VAO need to be here.

It is the work of my renderer to manage the scene? (Group object in a large VBO, hide object out of screen, Order object by transparency, …)

More explications on my architecture:

Spacial : Spacial element containing spacial elements (like a node).
Mesh : Object with a geometry and a material
Scene : Manage spacial element (like mesh) and lights.
Renderer : Draw the given scene (mesh and lights)

Where I should manage buffers (Index buffer, Vertex Object Buffer and Vertex Array Buffer)? In first, I started to put them in the Geometry class, but it seem obvious because a buffer can stock multiple Geometry object.

So, I'm thinking to put buffers in a buffer manager (in the scene object) -> Scene can manage meshes (order + static/dynamic to regroup them in buffers).

What do you think about that?

Thanks!


texts: What LuaJit threading archietecture should I use?

texts:
I am in the process of designing my own Game Engine for use in a real time CRPG - think Baulder's Gate. I know most of my specifications right now, and I am currently in a planning phase.

I chose Lua for a good number of reasons.

Fast and real time iteration.
Easy to lay out data and serialize tables.
Easy to learn for other programmers.
Can design tools to automatically write scripts for certain entities

For the first reason, I decided to have as much of my game code handled inside Lua as possible. With the exception of low level systems being handled inside of C++: Audio, physics, animation, rendering, resource managers(?).

But I came to a problem when it came to threading. I settled on using a job system. But I am not sure how to approach this with a heavy emphasis on Lua.

My Update look will look something like...

Local dt {}
While Game.isRunning() {
    dt = timer.delta();
    PreUpdate(dt);           //Delayed Raycasts for AI, Physics Triggers
    UpdateLogic(dt);         //AI, UI, Event Handling, etc.
    UpdateAnimations(dt);    //State Machines, Blending, framed scripts
    UpdatePhysics(dt);
    Render(dt);
}

How should I approach threading this?

My first thought is that I have only one VM of Lua, and set it on the main thread; then, the worker threads will work only in C++. Lua will have C++ API callbacks. When Lua calls this callback, it returns to C++. The C++ will create a job to be dispatched. The job is placed inside a qeue and processed on other threads in native code. I was thinking of following this idea. Most games seem to handle Game Logic in a serial manner -UpdateLogic(dt)-, then asynchronously updates lower level systems, multi-thread rendering, or handle events that are needed to fire immediately.

My Second thought is to use a job system with all threads using a Lua instance. I guess with this system I would be able to update entities in a threaded manner. But I can quickly see the problem. Because an entity's data is mutable, this can quickly cause logical errors. Even if I decided to defer updates to data, I can still see this becoming a problem with math errors.

Any guidance would be helpful here.


texts:
I am creating a game with HTML5 canvas for browser. I want to create animations with many shapes, which would be drawed with canvas, not from spritesheets.

The problem i face now is - to create formulas for so many shapes. I need them resizeable, also different width/height ratio. I was drawing chess pawn, but took 1 week to complete it right using arc's.

This is that pawn formula:

function pawn_shape(ctx, xx, yy, fill, stroke, grid_size) {
  var g = grid_size / 100;
  g *= 0.8;
  ctx.lineWidth = grid_size / 10;
  xx += g * 12;
  yy += g * 10;
  ctx.fillStyle = fill;
  ctx.strokeStyle = stroke;
  ctx.lineJoin = "miter";

  ctx.beginPath();

  var x = xx + 50 * g;
  var y = yy + 25 * g;
  var radius = 10 * g;
  var startAngle = 0.8 * Math.PI;
  var endAngle = 2.2 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 55 * g;
  y = yy + 48 * g;
  radius = 15 * g;
  startAngle = 1.6 * Math.PI;
  endAngle = 2.4 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 50 * g;
  y = yy + 97 * g;
  radius = 35 * g;
  startAngle = 1.7 * Math.PI;
  endAngle = 1.955 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 30 * g;
  y = yy + 92 * g;

  ctx.lineTo(x, y);

  x = xx + 50 * g;
  y = yy + 98 * g;
  radius = 35 * g;
  startAngle = 3.055 * Math.PI;
  endAngle = 3.3 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 45 * g;
  y = yy + 48 * g;
  radius = 15 * g;
  startAngle = 2.6 * Math.PI;
  endAngle = 3.4 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);
  ctx.stroke();
  ctx.fill();
  ctx.closePath();
}

This is only 1 pawn. I need many more figures as configurable formulas.
What would be the ways to get faster such formulas?

So far I am thinking about a new open source project, where people could draw shapes and these would be converted into such formulas. Or maybe even extract formulas from simple images, like programs do image to vector.

Another idea was to find out how does normal vectors work - what formulas they have. Maybe i could reuse and modify that? No idea, hoping to find answer here..


texts:
Recently, I was browsing the UE4 source code. I was especially interested in the OpenGL implementation on Windows. The OpenGL "Dynamic RHI" (as they call it) implementation can be found in the Engine\Source\Runtime\OpenGLDrv\ directory.

Contexts

After digging the code, I found out that they have multiple contexts with shared data. At the time of the RHI initialization they create two different contexts (FPlatformOpenGLDevice ctor)

SharedContext which will be the "parent" of every other context
RenderingContext that shares data with SharedContext

From now on, every time a new window is created and a context/viewport creation is requested, a new OpenGL context is created (PlatformCreateOpenGLContext function). Of course these contexts also share data with the SharedContext.

These contexts also own a VAO and a FBO (expect the viewport contexts where the VAO is not created for some reason; see PlatformCreateOpenGLContext function).

OpenGL "facts"

According to multiple sources:

A context can only be active in one thread at a given time
To issue gl* calls, you need an active context (of course)
The drivers basically run in sequential mode - so sending gl commands from multiple threads from multiple contexts will be "queued up" and will be executed in a sequence. And even worse this could cause context switches back-and-forth
So basically there is little or no gain by using multiple contexts (if we are using a single window to render into)

UE4 threading

As far as I know (and according to the source code and the documentation) they have a separate "rendering thread" that is used to execute gl commands. There are multiple functions that are interesting:

PlatformRenderingContextSetup which sets up the rendering context in the current thread (with a little "trick" on Windows)
PlatformBlitToViewport which displays the image on a specific target

My goal

I'm currently working on a basic engine (as a hobby and for educational purposes, needed by the universtiy) that must support multiple windows and "threaded loading". It is important that the resources loaded must be accessible by every window (context) so a shared context will probably be used (that's why I was interested in the UE4's approach).

Also I'd like to understand the reasons behind the UE4 devs' decisions and how their rendering works from a threading + context point of view. Currently I'm not interested in the actual render commands and technologies like deferred shading and so on.


texts: Object moving in a hollow pipe, want collision detection, how do I do that?

texts:
Do I need to add a rigidbody and sort the collider to fit to both the pipe and the object? I'd like the game to end if the object touches the pipe.

I've only seen sphere and box colliders. How would it work with a hollow pipe?


texts: The purpose of using invert and transpose

texts:
In openGl ES and the World of 3D - why use the invers matrix?

The thing is that I dont have any intuition to, why it is used, therefore please correct me:

As fare as I understand, it is used in shaders - and can help you to figure out the opposite direction of the normals?

Invers in ordinary numbers is like; The product of a number and its multiplicative inverse is 1. Observe that 3/5 * 5/3 = 1. In a matrix this will give you the Identity Matrix, which is the base coordinate system or the orion of the World space - right. But the invers is - some other coordinate system?

You can use the transpose(Row-major order to Column-major order) of a square matrix to find the inverted matrix, as calculating the invers is process heavy - and the transpose is giving you the inverted matrix as a bi product?

Again, I am looking for getting some intuition of this - and therefore be able to use it as intended. Thank you for any reply that will guide me in the right direction.

Regards


texts: Java create a Polygon for each island in tile game

texts:
I am making a 2d top-down tile based game, which is randomly generated each new world.

What I want to do is create a Polygon (or other more appropriate shape I don't know of) for each landmass not disrupted by land, basically each unseparated landmass/island, I want to do this for where my player is to spawn in the world, I want to have it so it has a higher chance of spawning on the biggest landmass in the world, rather than spawning on a tiny several tile island. So, all I need to know is how would I create some sort of shape system to recognise different islands.

The reason I suggest a Polygon is because the player would randomly spawn in that area so it has to be accurate to the land, it can't start of by spawning in water nearby.

If a Polygon is obsolete for this idea, and another system would be better let me know.


texts: I can't figure out how to animate my loaded model with Assimp

texts: I have loaded in a model to my C++ OpenGL game. It is a COLLADA file type that I have loaded, and I setup an animation under blender for the file. The problem is I don't know how to animate the model. The Assimp documentation didn't really help me out. Their source code didn't use animations, and I can't seem to find anywhere online that someone explains how to animate your loaded model... I'm sorta wondering if someone could link me to a helpful website, or maybe just help me out, so that maybe I will understand how to do animations with assimp.


texts: How to make an action perform only after an animation has run?

texts:
I have an actor who has some animations. Animations perform based on some actor states (animation blueprint of actor):

Conditions at the Event Tick (similar to while loop):

The actor changes perfectly from animation to animation. What I'd like to do is for it to damage an enemy as soon as the attack animation is over.

I tried some codes...

In this one, for example:

This variable (minionAtk) modifies the state of the actor. See the image below in the event (which is only called when the minionAtk is true) that I can successfully change the state of the actor (to the attacking state):

Animation Blueprint:

Transition:

But since the change from true to false is done instantly, the attack animation is not even shown.

To solve this, I put a delay and a condition so that the event could not be called again while the execution of cycle (attack animation => end attack animation) ended:

So when the actor is in the attacking state, the attack animation usually performs. After 5 seconds the animation stops.

It turns out that in this time interval the animation does not play only once.

I imagine there is a way to do the time calculation that the animation lasts, and based on that set the delay time.

But better than that, I wondered if there was no way to know when the animation was finished and from that, change the variable to false and perform the damage action.

Thinking about it I researched and found this:

https://answers.unrealengine.com/questions/329698/animation-damage.html

But I came across this error:

  This blueprint (self) is not a BTTask_BlueprintBase, therefore '
  Target ' must have a connection.

Error link:

https://answers.unrealengine.com/questions/549437/error-this-blueprint-self-is-not-a-therefore-self.html

I also saw something about sphere traces, attached to an actor socket. But in my case I don't want to apply the damage just in case of contact of the actor's arm (armed or unarmed) to the target, it would be something as seen in MOBA style games.

It would be like a basic attack from Garen/Yasuo/Darius.


texts: Is C++ being replaced by C# in industry games?

texts: In industry games I mean like Quake, CoD etc.


texts:
I am trying to find a way to divert a vector3 position around the surface of a mesh which doesn't have a collider. I have a function (found online) that calculates the closest position on the surface of the mesh but it only works if the position is outside the mesh.

In the diagram below, the red arrow represents whats currently happening. It works great when it's outside the mesh and will give a position on the surface of the mesh, but once it moves forward and enters the mesh, it just keeps walking straight. The green line shows what i would like to happen.


texts: Cut rest of image behind object (like POV)

texts: There are two objects - blue circle and black square. When you normally render them, you will see situation in "A". But how do I render only specific part of blue circle, which can be "seen" (is in sight) from red dot in middle of the circle ("B" situation)?


texts: Java/Android pixel perfect hit detection

texts:
I am making a game for android which I need hit detection between two objects. The first bitmap I have is a flying superhero, and the second bitmap is anything that he collides with.

The superhero bitmap is created on the fly by rotating the original bitmap between -90 and 90 degrees. As a result of the rotation, the bounding box is much, much larger than the non-rotated version. I have code to detect if the bounding box of the player hits any object, but visually this creates a problem when the object comes in contact with the skewed bounding box.

I need a solution that computes pixel-perfect hit detection between the player and the object, not just the bounding boxes.

I have been searching for the past 5 days for examples, tutorials, code snippets, or anything that could help me, but I haven't found a solution. The solution I'm looking for would be simply one function call similar to public boolean(obstacle theobject), where the obstacle's bitmap. coordinates, width, and height are returned with obstacle.getbitmap, obstacle.getx, obstacle.gety, obstacle.getwidth, and obstacle.getheight. The bitmap of the player is named rotatedbm and has global variables playerx, playery, playerh, and playerw.

I do not wish to implement external game engines or libraries.

I have read much on using int arrays with Bitmap.getPixels, and then comparing the arrays, but I cannot grasp the math behind comparing the arrays nor sorting out alpha values. I cannot afford to stay stuck on this one problem much long for the sake of development.

Thank you

EDIT- This is my implementation of the pseudo code. In the log, 'hit true' is never thrown but 'hit trying' is. Its not working as intended...

public boolean gethit(obstacle second){

        int px,py,ph,pw;

        Bitmap sprite1 = rotatedbm;
        Bitmap sprite2 = second.getgfx();

        px = playerx;
        py = playery;
        ph = sprite1.getHeight();
        pw = sprite1.getWidth();

        int ox = second.obx;
        int oy = second.oby;
        int oh = second.obh;
        int ow = second.obw;

        int [] AABB1bl = {px, py+ph};
        int [] AABB1tr = {px+pw, py};
        int [] AABB2bl = {ox, oy+oh};
        int [] AABB2tr = {ox+ow, oy};

        AABB2bl[0] -= AABB1bl[0];
        AABB2bl[1] -= AABB1bl[1];

        AABB2tr[0] -= AABB1bl[0];
        AABB2tr[1] -= AABB1bl[1];

        AABB1tr[0] -= AABB1bl[0];
        AABB1tr[1] -= AABB1bl[1];

        AABB1bl[0] -= AABB1bl[0];
        AABB1bl[1] -= AABB1bl[1];

        int start_x = AABB2bl[0];
        int start_y = AABB2tr[1];
        int end_x = AABB1tr[0];
        int end_y = AABB1bl[1];

        int ALPHAMASK = 0xFF<<24; // assuming colors are represented as 0xAARRBBGG

        int alpha1;
        int alpha2;

        Log.i("hit", "trying");
        for(int x = start_x; x < end_x; x++)
            for(int y = start_y; y < end_y; y++) {
              alpha1 = sprite1.getPixel(x , y*sprite1.getWidth()) & ALPHAMASK;
              alpha2 = sprite2.getPixel(x + AABB2bl[0], (y+AABB2tr[1])*sprite2.getWidth()) & ALPHAMASK;
              if(alpha1 != 0 && alpha2 != 0) {
                Log.i("hit", "true");
                return true; // you'd probably wish to return after a colliding pixel has been found
              }
            }
        return false;
}


texts: I'm reading the OpenGl superbible 3th edition (well I plan to) and it's all in C. Since this book was written in 2004 and all the other later versions are written in C++, i was wondering whether or not OpenGl is still supported in C, and whether the relevant downloads required will still be available. I want to do it this way, because I'm more comfortable with C, and I'm still learning C++.


texts: My game's title is similar to other game's title. Will I get sued?

texts:
I have a game called 'Shapes Dodge' which is still in development. I figured out the name back in February when I began developing it. Since then I've been checking monthly the Google Play Store for games with similar titles and today I saw my worst nightmare coming true - there are a few games with a similar name:
https://play.google.com/store/search?q=shapes%20dodge&c=apps

I am worried about the first two games which both have the name 'Shape Dodge'.
So will I get sued if I publish my game with the name 'Shapes Dodge' ('shapes' with 'S' at its end) on the Google Play Store?

I want to emphasize that the content of my game is very different from these games' (different controlls, gameplay, graphics, music, etc), only the title is similar.

Please answer me as simple as possible because I am not very familiar with legislation, laws, copyright, trademark and so on.
Thank you! :)

Edit

So after serios consideration and brainstorming I figured out a new name for my app: 'Dodgy Shapes'. Obvously the amount of similarity with the other apps which contain these keywords (https://play.google.com/store/searchq=shapes%20dodge&c=apps) is much less. But do you think it is enough difference so that I won't have any problems in the future?

Again, thanks to all who responded. :)


texts: Optimizing Bullet and ODE Physics on consoles and mobile phones

texts:
I'd like to use either Bullet or ODE on low powered devices (mobile and consoles), but the frame rates are below the acceptable 25-30fps for simulations.

I've found that one articulated body by itself is enough to degrade the performance of either engine.

Are there optimizations or tricks I can use to get around these problems?


texts: How can I speed up Unity3D Substance texture generation?

texts:
I'm working on an iOS/Android project in Unity3D. We're seeing some incredibly long times for generating substances between testing runs. We can run the game, but once we shut down the playback, Unity begins to re-import all off the substances built using Substance Designer. As we've got a lot of these in our game, it's starting to lead to 5 minute delays between testing runs just to test a small change.

Any suggestions or parameters we should check that could possibly prevent Unity from needing to regenerate these substances every time? Shouldn't it be caching these things somewhere?


texts:
I am trying to make my cannon mouth rotate towards player, but the rotation is messed up and up I don't know how to fix it.
class enemyshoot:
    def __init__(self,x,y,height,width,color):
    # [...............]
         self.look_at_pos = (x,y)

 def draw(self):
      # [............]
        self.rect = self.shootsright.get_rect(topleft = (self.x, self.y))

        dx = self.look_at_pos[0] - self.rect.centerx
        dy = self.look_at_pos[1] - self.rect.centery
        angle = (180/math.pi) * math.atan2(-dy, dx)
        self.image = pygame.transform.rotate(self.shootsright, angle)
        self.rect  = self.image.get_rect(center = self.rect.center)

    def lookAt( self, coordinate ):
        self.look_at_pos = coordinate

My full enemyshoot class
shotsright = pygame.image.load("canss.png")
class enemyshoot:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y =y
        self.height = height
        self.width = width
        self.color = color
        self.health = 10
        self.hitbox = (self.x + -20, self.y + 30, 31, 57)
       #-------------------------------------------------------
        # Make a Reference Copy of the bitmap for later rotation
        self.shootsright = pygame.image.load("canss.png")
        self.shootsright = pygame.transform.scale(self.shootsright,(self.shootsright.get_width()-150,self.shootsright.get_height()-150))
        self.image    = self.shootsright
        self.rect     = self.image.get_rect()
        self.position = pygame.math.Vector2( (x, y) )
        self.isLookingAtPlayer = False
        self.look_at_pos = (x,y)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        window.blit(self.image, self.rect)
        self.rect = self.shootsright.get_rect(topleft = (self.x, self.y))

        dx = self.look_at_pos[0] - self.rect.centerx
        dy = self.look_at_pos[1] - self.rect.centery
        angle = (180/math.pi) * math.atan2(-dy, dx)
        self.image = pygame.transform.rotate(self.shootsright, angle)
        self.rect  = self.image.get_rect(center = self.rect.center)

        # ------------
        self.hits = (self.x + 20, self.y, 28,60)
        pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 60, 100, 10)) # NEW
        pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 60, 100 - (5 * (10 - self.health)), 10))
        self.hitbox = (self.x + 200, self.y + 200, 51, 65)
    def lookAt( self, coordinate ):
        self.look_at_pos = coordinate

black = (0,0,0)
enemyshooting = []
platformGroup = pygame.sprite.Group
platformList = []
level = ["                                                                                p               p           p                         p                        p        ",
         "                                       ",
         "                             ",
         "                                      ",
         "                                  ",
         "                           ",
         "                                      ",
         "                                      ",
         "                                    ",
         "                                   ",
         "                    ",]
for iy, row in enumerate(level):
    for ix, col in enumerate(row):
        if col == "p":
            new_platforms = enemyshoot(ix*10, iy*50, 10,10,(255,255,255))
            enemyshooting.append(new_platforms)

This is where the cannons rotate towards the player, wherever they are
        for enemyshoot in enemyshooting:
            if not enemyshoot.isLookingAtPlayer:
                enemyshoot.lookAt((playerman.x, playerman.y))


texts:
I've recently created a small galiga like game recently using JavaScript and HTML5. I've run into a bit of trouble saving cookies, the cookie saves, but then resets itself when the page is refreshed, my code:

function saveScore() {
 var date = new Date();
  date.setMonth(date.getMonth()+5);
  var expires = "; expires=" + date.toGMTString();
  document.cookie = "score=" + lvl + expires + "; path=/";
}

function loadScore() {

  var cookiearray = document.cookie.split(';');
  for (var i = 0; i < cookiearray.length; i++) {
    var name = cookiearray[i].split('=')[0];
    var value = cookiearray[i].split('=')[1];
    if (name == "score") {
      alert("Prior score found. Loading score...");
      lvl = value;
    }
  }
}

EDIT:
It appears as though I made an error outside of the given code, and reset the level to zero, I fixed this, and everything works well, I apologize for any confusion caused.


texts: Integration of gravitational interaction

texts:
I don't know if this question get her place in physics.stackoverflow forum. I prefer post here, with code etc.
So, I want simulate 2D movements (no rotation) of an asteroid in space affected by a planet's gravity, the problem is how integrate that ?
Any better integration for performance ?
Here is the code in C:
struct vec2
{
  float x;
  float y;
};

struct body
{
  double mass; //kg
  struct vec2 prev_pos; //for semi-implicit euler method
  struct vec2 pos; //position
  struct vec2 v; //velocity
};

void move_asteroid(float dt) {
  //semi-implicit euler integration #1 -moving the object
  asteroid.pos.x += asteroid.v.x * dt;
  asteroid.pos.y += asteroid.v.y * dt;

  //START
  float x = planet.pos.x - asteroid.pos.x;
  float y = planet.pos.y - asteroid.pos.y;
  float d = x * x + y * y; //distance^2 between asteroid and center of planet

  //acceleration
  float ah = G * ((planet.mass * asteroid.mass) / d); //gravity

  //get components of gravity
  float rad = atan2(y, x);
  float ax = ah * cos(rad);
  float ay = ah * sin(rad);

  //semi-implicit euler integration #2 -update velocity
  asteroid.v.x += ax * dt;
  asteroid.v.y += ay * dt;
}

this is for 'fun' and sadly my knowledge is quite not good, I try to find with my vocabulary (not native english), if you have directions, ideas for better implementation (like study RK4 for correctness etc), it's welcome


texts: Create YUV texture for GL_TEXTURE_EXTERNAL_OES format

texts:
0
down vote
favorite

I need to create a yuv texture for GL_TEXTURE_EXTERNAL_OES format.

source : https://github.com/crossle/MediaPlayerSurface/blob/master/src/me/crossle/demo/surfacetexture/VideoSurfaceView.java

I am doing all processing on YUV, so it would save clock cycles, if I can generate a yuv texture as output of texture2D.

To get 'y' value, I need to take dotproduct of each texel with vec3 of (0.3,0.59,0.11) Since, for my purpose I need to take 3x3 pixel block's 'y' value and take a convolution of them, this results in performance impact. So it would save clock cycles, if I can generate a yuv texture as output of texture2D.


texts:
By collectibles, I mean objects that you collect mainly for the sake of collecting them, not to power up. Think coins in Super Mario or bandages in Super Meat Boy.

I've seen a few platformers that do not have any collectibles and it's the platforming itself which is challenging (my platformer itself is challenging), but I think adding collectibles will add extra challenge and re-playability, especially if some of the collectibles are really well hidden. Tradition would dictate that you should have collectibles, as it's a way for players to gain extra lives or even gain points, but that would not be the only reason to have collectibles.

I'm not interested in making features for feature sake. I'm purely wanting an opinion on whether collectibles should be included in a game and what should the collectibles do when you collect enough? Is a simple +1 life fine? Should there be some cool object you get? Possibly should collecting really change something hectic, like collect 100 coins and your character is invincible?

How do I decide if my platformer should have collectibles?

Closed. While I disagree with the closing as according to the FAQ What should be asked game design (level design, gameplay, mechanics, etc). I got some nice pros and cons from everyone. I have updated the question slightly to be more specific.


texts: Determine the bullet / particle reflection off of a circle in node js using SAT lib functions

texts:
I can see how the calculation should occur from other examples such as: How to bounce a 2d point particle off of a circular edge.

But I could use some help with the specifics for my inputs given during a game loop that is progressing / moving the bullet each game loop tick, and then detecting and handling collisions.

I've tried to mock up an example nodejs script using the SAT lib
http://requirebin.com/?gist=4a5c208dc39d3c3be262abb05fa791a3
.. with the console logs tracing a few variables, including the output target vector.

My question essentially lies in understanding how I can use the SAT vector functions like dot() or reflect() to produce the reflection?

https://github.com/jriecken/sat-js#classes

Even pseudo code would help me understand what exactly the operation needed to determine the reflection point (not just the angle, but the bullets new target vector) given my inputs of a bullet x,y position colliding with and a circular wall.


texts: LAN multiplayer game for desktop and Android in Unity 3D

texts:
How can I add an option "Multiplayer on LAN" to my desktop and Android game? I am using Unity 3D, and I am currently building a chess game.

Just give me the source or a specific path that I have to follow. Any shared material or criticism will be appreciated.


texts: Okay, so I know I need to set the path to the native files. I can do this in Eclipse, by going to the VM arguments and using -Djava.library.path=, but when I export, it says that the VM arguments aren't kept after exporting, but it can be set in the console while running it. I am running Mac OS X. How do I set that using Terminal?


texts: Why is a fully transparent pixel still rendered?

texts:
I am trying to make a pixel shader that achieves an effect similar to this video http://www.youtube.com/watch?v=f1uZvurrhig&feature=related

My basic idea is render the scene to a temp render target then
Render the previously rendered image with a slight fade on to another temp render target
Draw the current scene on top of that
Draw the results on to a render target that persists between draws
Draw the results on to the screen

But I am having problems with the fading portion. If I have my pixel shader return a color with its A component set to 0, shouldn't that basically amount to drawing nothing? (Assuming that sprite batch blend mode is set to AlphaBlend)

To test this I have my pixel shader return a transparent red color. Instead of nothing being drawn, it draws a partially transparent red box.

I hope that my question makes sense, but if it doesnt please ask me to clarify

Here is the drawing code

    public override void Draw(GameTime gameTime)
    {
        GraphicsDevice.SamplerStates[1] = SamplerState.PointWrap;

        drawImageOnClearedRenderTarget(presentationTarget, tempRenderTarget, fadeEffect);
        drawImageOnRenderTarget(sceneRenderTarget, tempRenderTarget);
        drawImageOnClearedRenderTarget(tempRenderTarget, presentationTarget);

        GraphicsDevice.SetRenderTarget(null);

        drawImage(backgroundTexture);
        drawImage(presentationTarget);

        base.Draw(gameTime);
    }

    private void drawImage(Texture2D image, Effect effect = null)
    {
        spriteBatch.Begin(0, BlendState.AlphaBlend, SamplerState.PointWrap, null, null, effect);
        spriteBatch.Draw(image, new Rectangle(0, 0, width, height), Color.White);
        spriteBatch.End();
    }

    private void drawImageOnRenderTarget(Texture2D image, RenderTarget2D target, Effect effect = null)
    {
        GraphicsDevice.SetRenderTarget(target);
        drawImage(image, effect);
    }

    private void drawImageOnClearedRenderTarget(Texture2D image, RenderTarget2D target, Effect effect = null)
    {
        GraphicsDevice.SetRenderTarget(target);
        GraphicsDevice.Clear(Color.Transparent);
        drawImage(image, effect);
    }

Here is the fade pixel shader

sampler TextureSampler : register(s0);

float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 c = 0;
    c = tex2D(TextureSampler, texCoord);
    //c.a = clamp(c.a - 0.05, 0, 1);
    c.r = 1;
    c.g = 0;
    c.b = 0;
    c.a = 0;
    return c;
}

technique Fade
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}


texts: How do I efficiently deal with entities moving between chunks?

texts:
I am working on a game in which entities need to be stored in chunks.

This is the basic chunk format:

public static Entity [row][column][entities] chunkEntities;

However, some of my entities move. How do I handle an entity switching chunks as a result of moving, and what is the most efficient way of doing so?


texts: Is it possible to billboard a sprite using a transformation matrix?

texts:
None of the current topics on billboarding seemed to answer this question.

But, given

a sprite (or quad) that has it's own 4x4 transformation matrix
a camera with a view matrix (a standard 4x4 transformation matrix)

is it possible to compute a 4x4 transformation matrix such that when the quad's matrix is multiplied with this matrix it has an orientation of looking at the camera?


texts: Looking for Bezier curve OpenGL open source implemention

texts:
well in short im looking for something like this as open source.
https://www.youtube.com/watch?v=Cut3_A0Xm3Y

i need to implement especially the Bezier curve editing in my app in open gl .
any ideas where i can find such open source implementation ? ( can be c++ or java )


texts: Get a Vector2 Based on Object Rotation in Unity

texts:
I feel like there is an obvious answer to this but I can't find it. Is there a function in unity that gives you a Vector2 (or 3) based on the rotation of an object.
for example:
z rotation = 0 ---> (0,-1)
z rotation = 90 --> (1,0)
z rotation = 180 -> (0,1)
z rotation = 270 -> (-1,0)
I could just write this in my script the long way, but I feel like there might be a function for it in unity


texts: How do I get the position and rotation of an animated object in Unity?

texts:
I have this object which is being animated, the animation moves a arm and hand. I want it to look like it's holding something but I can't move the object to the hand because even though the animation appears to move the world position of the animation object stays the same, the objects parent is the hand but it's still not moving to it. So how do I move the object to the animations hand while it's being animated in unity?

Maybe this could help to visualize what my problem is:

I found another way around the problem: attached the object as a child of the bone instead of the hand mesh. I still don't know why it didn't move with the hand.


texts: Sorting layer issue with multiple sprites and a Tilemap in Unity

texts:
I have a particle system that draws a blood splat. I have a Tilemap that represents terrain. However, the blood splats, which are on a sorting layer in front of the terrain, are somehow rendered both in front of and behind the terrain.

I have encountered similar problems before where the particles had some different Z value than the terrain, but that is not the case this time (3D view):

Here are the Inspector panels for these objects.
First terrain:

The renderer for the upper (in Y) blood particle system:

And for the lower (in Y) system:

And finally my sorting layers, where Base is behind Foreground:

What might cause this behavior and how can I fix it?
Edit: Here is the entire BloodSplat prefab:


texts: How to implement a track for a wipeout-style game on a mobile device?

texts:
I was wondering what is the best way to manage a 3D track for a game with the same mechanic as Wipeout on a mobile device. Build a track out of multiple segments and load new segments as the player advances or build just one single mesh, maybe with multiple level of details ?

I'm very unfamiliar with this kind of problems so suggestions for other approaches are welcome.


texts:
I am running into an issue with my UI.
Basically I need to have a lot of small icons, similar to many other games, here is an example:

With Mip maps:

As you can see, these look awful. This is simply a UI Image with size 15x15, it seems when they get too small it simply does not look good. It has nothing to do with import options or anti-aliasing, I have tried everything there. I submitted it as a bug but according to Unity it simply will not look good when images are scaled down too much.I have tried both PNG with large resolutions and small, I have exported the .SVG vector image and tried using that, all look bad when scaled down.
So what are my options then when I need small icons? How do other games do it?
Here is a link to the actual .png file: https://ibb.co/nDG0hmD
For reference, here are the same icons zoomed in, as you can see, they look fine:

Im developing for PC.


texts: How to link my weapons with their corresponding ammo supply in the Unity Inspector?

texts:
In my game I would like to implement a universal ammo and weapon system that would be usable for any kind of weapon. So I declared an ammo class:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Ammo {

     public int MaxAmmo;
     public int CurrentAmmo;

     public Ammo(int maxAmmo)
     {
         MaxAmmo = maxAmmo;
     }

     public void MaxOutType()
     {
         CurrentAmmo = MaxAmmo;
     }

     public void GetAmmo(int amount)
     {
         CurrentAmmo += amount;
     }

     public void UseAmmo(int numOf)
     {
         CurrentAmmo -= numOf;
     }
 }

Then I created a script to hold different Ammo types:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AmmoSystem : MonoBehaviour
{
    [SerializeField]
    public Ammo Basic = new Ammo(200);
    public Ammo Rockets = new Ammo(50);
    public Ammo AirRockets = new Ammo(75);
    public Ammo Cells = new Ammo(150);
 }

To organize my project I decided to make two weapon scripts: one for nonphysical(Raycast) projectiles called RaycastingWeapon and an another for physical ones(like a rocket launcher) called PhysicalProjectileWeapon

My plan was to create unique weapons using these two scripts from the inspector.

These would use different kinds of ammo but would share the same script with different properties. The essential aspect here is that I would like to be able to select an ammo type from the inspector using a dropdown menu for example.

Is it possible somehow or are there a better way of doing that?


texts:
How long is SystemInfo.deviceUniqueIdentifier?

The official docs say nothing about it. Obviously I can do a few tries, but these will definitely not be conclusive: did someone either gather extensive data, or somehow analyzed the algorytm that creates it?