texts: Raycasting in three.js not working properly on ipad and touch devices

texts:
I am working on a 3D tool for desktop and iPad. Everything is working fine except for two issues:

Issue 1 - When I select a 3D object with the mouse and move it on an iPad (as opposed to on desktop, where it works just fine), it doesn't move. (You can add cabinet by selecting the cabinet panel in right).

Issue 2 - I want to spawn and drag an object with the click of a button like this.
With this tool, you can add an object by selecting and dragging it to the scene.

Thanks in advance. :)


texts: How to implement user friendly screen panning on 3D HTML canvas for RTS game

texts:
How can I get RTS map panning like how it was done in C&C red alert (with the mouse at the edge of the screen moves the screen in that direction) with a Babylon.js RTS game in the html canvas? This would be simple should I force the game to be full screen, but I don't think this would be practical.

I was thinking of checking that the mouse is near the edge of the canvas to pan but this could be annoying for the user. Perhaps I could force the mouse to be in the bounds of the canvas (in non fullscreen mode) until the user presses some shortcut key, but again I could be breaking the browser experiance.

Your advice?


texts:
I showed my friend a demo of what I was doing with the farseer physics engine on the windows phone and he wanted to know if farseer would be good for a game he wants to develop. It's a tile based game so I said I don't think farseer would be the best choice (correct me if i'm wrong).

Are there any tile game engines for windows phone? Think tile based like the original Zelda.


texts: Change layout of Unity's Project->Assets pane contents to show longer filenames?

texts:
I'm working on a project with assets that have really long filenames. I know about the slider in the lower-right corner of the Project->Assets pane, but THAT slider makes the icons absolutely HUGE & only allows the display of filenames that are slightly longer than the default.

Is there a way to either:

Get Unity to use a view akin to Windows Explorer's "List" view (small icon on the left, long filename on the right)
Get Unity to truncate long filenames in the middle? For example...

Full name: ExtraordinarilyLongFilename-27a.material
How it displays now: ExtraordinarilyLongF...
How I'd like it to truncate: ExtraordinarilyL...e-27a

(the general assumption of a middle-truncated long name being that the last few characters are usually the ones that distinguish between multiple files that all begin with the same prefixes)


texts: I can't set the Source image for a UI image; how to fix it?

texts:
I am new to Unity. As a learning project, I started to make a very basic car racing game. In order to add an on-screen speedometer for my car, I imported an image UI.

The problem is that I can't set a source image for my speedometer UI. I tried using .jpg .png or .psd image files as well. In any case, I'm not able to drag and drop the image.

Under the list Source Image, I already have selected UISprite from the drop-down list, but still, I'm not able to set source image.

Can anyone provide me any solution? I also have attached a screenshot of what I have.


texts: Visualize quaternion euler angles without gimbal lock

texts:
I fusion ACC and GYRO data with Mahony algorithm, and then I want to show a line chart representing roll pitch and yaw to the user, so they can understand the degrees. As you can imagine, gimbal lock comes in at 90 degrees.

I also have an activity where the user can see a cube rotating correctly, having quaternions as input.

Is there a way to visualize the angles in degrees without gimbal lock? I can only manage to show an OpenGL shape rotating correctly, but my goal is to show the degrees.


texts: (Optimization) Efficiently discovering if a new day has been reached

texts:
I'm making an in-game clock/calendar system. In-game time is 12x real time. In addition, in-game events can fast-forward time. I also have in-game events that reset or trigger at the turn of each day.

My issue: I don't want to perform an end-of-day check every time there's a frame update, like:

void Update(float _delta) {
    gameTimeInSeconds += _delta * timeScale; // time scale is 12.
    while (gameTimeInSeconds >= currentDay * 86400.0)
        NextDayReached();  // increments currentDay, and updates in-game events.
}

It feels inefficient to make the check on every frame. Is there a more efficient way to determine when a new day has been reached?

Or am I worrying over an ultimately tiny issue?


texts: WebGL Multiple Lights, Blending, and Render Order

texts:
I am trying to do simple forward rendering for multiple lights using additive blending in WebGL. Following advice from this SO and this one, I simply turn on blending using glBlendFunc(GL_ONE, GL_ONE) and glEnable(GL_BLEND).

However, while this is combining the contribution from multiple lights, it is also making everything "transparent", as in the front faces of my object are blending with the back faces. I know that rendering transparent objects requires sorting the objects by depth, but this would be extremely slow in javascript, and doesn't seem to be necessary as blending should only occur when faces are at equal depth, which is something the depth test/z-buffer should be able to handle, right?

So is sorting the objects really necessary for forward rendering of multiple lights?


texts: How to differentiate landing on top of an object from falling down the side?

texts:
I am looking for a conceptual solution to my problem. It's a simple platformer-alike game where player can move horizontally during free-fall.

Consider those two cases:

In the first case, from game experience point of view, the player should land on top of the box; and in the other case he hit the left edge, hence the player should fall down.

However, from my code point of view ("real behaviour"), both those collision detection cases are identical. I am not sure how to separate them.

In both cases the vertical velocity is positive (falling down) and the user is moving with some fixed positive horizontal velocity. (moving right)

From a collision-standpoint the two cases are identical, I think. How can I tell whether I should put the player on top of it or let him fall?


texts: Spherical procedural terrain shader based on slope

texts:
I've created a spherical terrain object out of 6 sphere projected (normalised) planes, each plane has been heightmapped post to being normalised.

I'm looking to create a CG shader which will firstly calculate the slope of the heightmapped terrain, I understand this will need to look at the normals to calculate this can anyone elaborate on this for me? The next problem is that I want to do the slope calculations based upon the terrain "flat" rather than normalised.

Would it be best to either reverse the normalisation of the vertices during the slope calculations, or pre calculate and store the vertices slope data (on the flat plane) during the mesh generation?

This is an example of what I want to achieve with the shader:

Any suggestions would be brilliant.

Thanks, C.

Update in response to opatut answer:

I've output the current slope data based of how I "think" was suggested and these were the results:

I think my issue is that as each plane begins to curve that curve is includes as a slope which is the obvious thing to happen. I want to "flatten" out each of the 6 planes again for the slope calculations.


texts:
Android Launch error
My sdk settings:

LogPlayLevel: UnrealBuildTool: Preparing native code for debugging...
!LogPlayLevel: UnrealBuildTool: UnrealBuildTool Exception: ERROR: D:/Program Files/NDK/NVPACK/android-ndk-r12b/ndk-build.cmd failed with args APP_ABI="arm64-v8a " NDK_DEBUG=1
LogPlayLevel: CommandUtils.Run: Run: Took 36,7394016s to run UnrealBuildTool.exe, ExitCode=5
LogPlayLevel: BUILD FAILED
PackagingResults:Error: Error Launch failed! Unknown Error


texts:
I don't know of this is possible or not. I was following Unity - The NavMesh Agent tutorial.
What I'm thinking on how to make the agent take's different path ? example, if i have two agents, how to make both of them taking different paths ?


texts:
I'm currently using a xbox 360 controller on my windows 10 computer. I've been trying to find how to use the LT and RT buttons on my controller to shoot and aim. Can some one give me an example on how to receive and use input with these buttons? I am using javascript, so it would be helpful to have it in that programming language!
Thank you in advance!


texts: What libgdx project files can I ignore from version control?

texts:
In an automatically created libgdx project, what files can I safely tell Git (or other revision control systems) to ignore?

I'm considering these:

*-android/.settings/
*-android/bin/
*-desktop/.settings/
*-desktop/bin/
*-html/.settings/
*-html/gwt-unitCache/
*-html/war/WEB-INF/classes/
*-html/war/WEB-INF/deploy/
*-html/war/assets/
*-html/war/
*/.settings/
*/bin/

Am I missing some? Is there a complete list somewhere?


texts:
I'm creating platforms in my game where the player can:

1) Jump through them from the bottom and land on top of them

2) While on top of them, drop down through them

I've been able to get #2 working just by disabling the contact using contact->SetEnabled(false) and this has worked fine. I'm mainly having some issues on the best way to handle #1. Here's the basic idea I have, though there's still some things that I need to concretely figure out. (Note: The logic below is very Box2D specific, but should apply to most physics engines):

Add 4 sensor fixtures to the 4 sides of the main fixture that extends a small amount past the main fixture
When the top, left, or right sensor fixtures make contact with a platform, disable the contact by using contact->SetEnabled(false) and set a boolean flag inside the Sprite object indicating that the Player is passing through the platform
When the bottom fixture ends contact with the platform, disable the boolean flag

This would basically make the top, left, and right fixtures act as enablers for the pass through logic and the bottom fixture act as the disabler. So when the player is falling back down from their jump, the bottom fixture will make contact, but won't disable the contact.

This makes sense on paper, but I can think of a few corner-case issues that might arise from this. Before I start plugging down this path, does anyone have any suggestions that might make my plan better or even a completely different way of doing it?


texts:
I have a sprite which has Velocity and Position, either stored as Vector2. At each Update cycle, velocity is added to the position.

I would like to give the sprite a third vector, Target. New targets may be given at any iteration. I would like the sprite to essentially move in a random walk pattern, however two parameters must be exposed:

A typical random walk is equally likely to increase or decrease the distance to any given Target (plus the small chance of tangential movement). I must be able to bias my random walk such that, while still random, the direction on which the sprite "decides" should be more likely to bring it closer to Target.
The random walk should be "smooth"- the sprite should not rapidly change direction, as this will look like it's "flickering" or "trembling" to the player. It should gradually veer this way or that, moving randomly, while slowly getting closer when averaged.

What is a good, simple way to do this? If possible, give the answer as a Vector2 RandomWalk(Vector2 target) method.

I already have a NextGaussian(mean, stdev) method available, if that is helpful.


texts: 2D narrow-phase line intersection with square bounding box for calculating height efficiently

texts:
I've performed partitioning of my level into broad and narrow phase. I'm down to narrow phase and focusing on the height from the ground.

I want to see what polygon the player is on top of. Since some polygon sectors may be lower than others (this is a birds eye view), I want the player to be stand on top of the highest one. Therefore I thought what I can do is each game tick would be to check which boxes the player intersects, and then find the polygon with the highest 'height' and use that as the base height for the player.

An example would be below:

Is this a viable way of doing it? That this game is 3D, but I only have to do two dimensional calculations for the height which reduces the computation and makes this easier.

The level has been cut up into a BSP tree so the following is a gross misrepresentation of the level, however I don't see any obvious way (immediately) to exploit the BST property to find out the highest sector that the player would be standing in. So far the best way I could think of was to use narrow phase collision detection described above and hope that is extremely fast.

I am looking for speed here, so if you know of any better algorithms or some faster way of doing this, please let me know.

EDIT: The focus of this post is for high level algorithms, of which they can be optimized later on. No actual collision detection code has been made yet.


texts: Unity splash is starting in progress after white screen

texts:
When I export my Unity project (on Windows), there is a brief white screen before the Unity splash screen renders, already in progress. Discretely cutting to the already in progress splash screen looks pretty bad, so I'd like to fix this.
Here is a video showing what I mean.
After some googling, I did find other reports of a white screen, but only on Android. My project is very simple and I am not loading anything intensive on boot, so I'm not sure what is causing this white screen.
Does anyone know what might be causing this issue or have ideas to troubleshoot it?


texts:
I have started making a 3D game in Unity5 that consists in avoiding obstacles. It is very easy but I want to add a collision effect when I collide on the wall.

I would like to slice the screen into many parts (random pieces is better) that are falling down from screen with gravity.

An example of what I mean:

How can I do this?
I've tried using a lot of different images (shapes) but I'm sure that is not the best way...

Thanks for any suggestions.


texts: Dot Product Vs Cross Product Turning a Turret Towards A Enemy and firing

texts:
http://pastebin.com/iw9DHf7s is code demonstrating dot product turning a turretto a target and firing. It works and chooses best angle to spin.

A problem can occur when game goes faster (better computer) and that threshold no longer applies. Making the threshold bigger obviously stops the turret early.

My friend mentions cross product is the way to fix it. Then he disappears for long periods of time. Doesn't dot product NOT get a inner angle between two vectors? Ok lets just say I agree and dot product doesn't work ever.

So tell me how does vector product do the trick? I'm going from a single scalar that I can get degrees out of to a third orthogonal vector. I've read about cross product and the function and watched a you tube video and I don't get (given the same code pasted) how to use cross product here.

Update:
Would this work?

//towerFacing is the at/forward vector of the cannon
Vector v1 = cannonPos - targetPos ;
Vector v2 = towerFacing - cannonPos ;

//The z plane
double cross = v1.x*v2.y - v1.y*v2.x ;
if (cross > 0) { return Direction.Left ; }
if (cross < 0) { return Direction.Right ; }

Obviously the zero is not what we want to use in games. However The difference is now our zero means our at vector and target is perpendicular and on each other which a x b = 0. The dot product since it uses cosine I used the right vector which is orthogonal with the facing( a . b = 0).

Am I wrong on how the cross product works by what has listed for answers still?


texts:
I'm trying to make my game as friendly to multi-core as possible. as such, i'm putting each animation on a new thread. I was hoping someone could check out my proof of concept code in java;

an example of usage is as follows:

    ThreadedAnimation ta = new ThreadedAnimation();
    Thread tat = new Thread(ta);
    tat.start();
    ta.getCurrentFrame();

where the threadedAnimation class is as follows:

public class ThreadedAnimation implements Runnable{
boolean init = false, toFinish = false, toStop = false; //synchronized info
short[] delay; //delay in ms
Image[] frames; //array for the frames
public Image currentFrame = null; //for pulling the frame
int currentFrameNumber = 0; // simmillar representation. to go barebones, I would just return the int and not the number.

public ThreadedAnimation(short[] del, Image[] fram){
    if(del.length == fram.length){
        currentFrame = fram[0];
    }else{
        System.out.println("bad animation detected");
    }
}
public ThreadedAnimation(){
    delay = null;
    frames = null;
}

@Override
public void run() {
    if(init){
        while(!toFinish && !toStop){
            currentFrameNumber = 0;
            while(!toStop && !(currentFrameNumber> frames.length)){

                long currentTime = System.currentTimeMillis();
                while((System.currentTimeMillis()-currentTime) < delay[currentFrameNumber]){// The reason I don't put TrySleep(delay[i]) is because the thread is interrupted every time we try and get the image.
                    TrySleep(10);
                }
                currentFrameNumber++;
                currentFrame = frames[currentFrameNumber];
            }

        }

    }
}

private void TrySleep(int i) {
    try {
        Thread.sleep(i);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}
public synchronized void  finish(){
    toFinish = true;

}

public synchronized void stop(){ //stops animation where it stands and kills
    toStop= true;

}

public synchronized Image getCurrentFrame(){
    return currentFrame;
}

}


texts:
I want to make cutscenes etc, in my game.

I thought of a similar System like in the RPG Maker:

If you enter a certain Area, a list of commands and arguments is played.

E.g. like this:

[Move Object: Right, right, right; Wait until done;]
[play Sound: sound.sfx]
[Show Message: Speaker: player, message]

I don't want to use external libraries.
Someone has a basic idea on how to implement this?

I thought of a "stack" for these kind of "events", but I'm not sure about it.


texts: Should I dedicate a single thread to each player in a split-screen game?

texts:
I was thinking about making multiplayer version of a game I am making with SDL and OpenGL. It would be a split-screen game.

Do you think it would be a good idea to have each part of the screen (game session) handled by different thread? Those threads would have no data to share except for pause and game over/victory events. Since the single player version is already written, I thought I could save a lot of development time by implementing it this way.


texts: How do you prevent AABBs from passing through each other?

texts:
I know what an AABB is, but I don't know how you would check for collision with an object that is going really fast. If an object goes fast enough, it can skip over other bounding boxes without it detecting a collision.

Example:

So, for an object with a bounding box to move from (0, 0) to (525, 670) in one update, would I have to somehow iterate over each point from the starting point to the end? Because I need objects to be able to go fast and still be tested for collision on other bounding boxes. I hope that makes sense.


texts:
I'm developing a video game using OpenGL as graphic API and C++ programming language, and I'm creating all models with blender.

One question I have is how you deal with models (vertices), I mean, once you have created a model and want to load them with OpenGL you use hard-coded or a software module to load them on runtime?.


texts:
I am making a shooting game, where I have a countdown as I destroy enemies. I want to implement logic when all the game objects are destroyed within the given time, and the countdown reaches zero.

How do I do that?


texts: (Unity3D) Determine If Ray Intersects Given Rectangle

texts:
I'm building a city generator for my game and I want to ensure buildings are never placed in such a way that they overlap roads. Currently I have the system build the roads, then place buildings alongside those roads.
I have the beginning and end points of the roads as Vector3s (only using X and Z, Y is never considered for road/building placement). For buildings, I use the size of their Box Colliders to check if they can fit in a given space (with rotation and scale applied appropriately). I've done a fair amount of research for answers on lines intersecting planes, though they always seem to be incredibly hard to follow or just don't properly apply to my situation (such as determining if the line is coterminous or not). I simply need to know if the line at any point exists within the bounds of the building's rectangle. I do not need to know where or at what angle.
I also understand that my problem is essentially a 2D math problem, as I'm ignoring Y, and some of the 2D solutions I've seen to this would be extremely costly to do in city generation.
Any help would be greatly appreciated.


texts:
I've never used the UDK before and I am wondering: is it possible to use the UDK through C++ instead of UnrealScript?

I saw it's possible to bind external C++ DLL's to UnrealScript, but I don't know if it's possible to call engine functions from inside C++ code.


texts: Moving all the particles in effect LIBGDX

texts:
I have a few particle effects that I would like to be in a circle shape
in libgdx i.e. not a cone shape. I have done this by setting the direction
of the particle effect from 0 to 360. The problem is that the particle effect
is moving. So, as the emitters are moving, but not the particles themselves,
the overall shape becomes conical. This could simply resolved by moving all the
particles along with the particle emitters, but I can't fnd any way of doing
this. I have considered drawing the effect to a Frame Buffer Object in one
position, then draw the texture to each new position. However, this would mean I would have to flush the SpriteBatch each time a draw a particle effect, and that would be very expensive.

Is there any  way to move the entire effect, with both the emitters and the particles?

Thannks in advance


texts: animation of an Actor in libgdx crashes on iphone

texts:
I am using a class found here on stackover for the animation of the actors , but I crash on the physical device

class AnimatedImage.java:

public class AnimatedImage extends Image
{
    protected Animation animation = null;
    private float stateTime = 0;

    public AnimatedImage(Animation animation) {
        super(animation.getKeyFrame(0));
        this.animation = animation;
    }

    @Override
    public void act(float delta)
    {
        ((TextureRegionDrawable)getDrawable()).setRegion(animation.getKeyFrame(stateTime+=delta, true));
        super.act(delta);
    }
}

create() method, get frames and add to the stage:

Array<TextureRegion> waveArrayTextureRegions = new Array<TextureRegion>();
for(int i = 1; i < 24; i++){
    waveArrayTextureRegions.add(new TextureRegion(new Texture("wave/4096/wave ("+i+").png")));
}
waveAnimation = new Animation(0.15f,waveArrayTextureRegions, Animation.PlayMode.LOOP);
waveActor = new AnimatedImage(waveAnimation );
waveActor.setWidth(Gdx.graphics.getWidth() / 1.05f);
waveActor.setHeight(Gdx.graphics.getHeight() / 1.05f);
waveActor.setPosition(0,0);
stage.addActor(waveActor);

I would add this class is animated actor , and , on Android no problem , but when I install it on my iPhone via RoboVM crashes . It ' possible that the class or something wrong with liking to the iPhone ? Additirruta on the iPhone simulator works only when I put it on the physical device I crashes in this class . can someone give me a help?


texts: how to make a humanoid character bone rotate to face an object in unity?

texts:
I want to character to be able to move in a direction and be able to aim to object in other direction.
I use code below to control bone of a character:

anim.SetBoneLocalRotation(HumanBodyBones.Spine, Quaternion.Euler(...));

but I don't know what is the right way to rotate chest and spine of a character to make upper body aim to a position.


texts: how can I specify interleaved vertex attributes and vertex indices

texts:
I'm writing a generic ShaderProgram class that compiles a set of Shader objects, passes args to the shader (like vertex position, vertex normal, tex coords etc), then links the shader components into a shader program, for use with glDrawArrays.

My vertex data already exists in a VertexBufferObject that uses the following data structure to create a vertex buffer:

class CustomVertex
{
public:
float   m_Position[3];      // x, y, z      // offset 0, size = 3*sizeof(float)
float   m_TexCoords[2];     // u, v         // offset 3*sizeof(float), size = 2*sizeof(float)
float   m_Normal[3];        // nx, ny, nz;
float   colour[4];          // r, g, b, a
float   padding[20];        // padded for performance
};

I've already written a working VertexBufferObject class that creates a vertex buffer object from an array of CustomVertex objects.  This array is said to be interleaved.  It renders successfully with the following code:

void VertexBufferObject::Draw()
{
if( ! m_bInitialized )
    return;

glBindBuffer( GL_ARRAY_BUFFER,          m_nVboId );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  m_nVboIdIndex );

glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glEnableClientState( GL_NORMAL_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );

glVertexPointer( 3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 0) );
glTexCoordPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 12));
glNormalPointer(GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 20));
glColorPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 32));

glDrawElements( GL_TRIANGLES, m_nNumIndices, GL_UNSIGNED_INT, ((char*)NULL +  0) );

glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
glDisableClientState( GL_NORMAL_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );

glBindBuffer( GL_ARRAY_BUFFER,          0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  0 );
}

Back to the Vertex Array Object though.  My code for creating the Vertex Array object is as follows.  This is performed before the ShaderProgram runtime linking stage, and no glErrors are reported after its steps.

// Specify the shader arg locations (e.g. their order in the shader code)
for( int n = 0; n < vShaderArgs.size(); n ++)
    glBindAttribLocation( m_nProgramId, n, vShaderArgs[n].sFieldName.c_str() );

// Create and bind to a vertex array object, which stores the relationship between
// the buffer and the input attributes
glGenVertexArrays( 1, &m_nVaoHandle );
glBindVertexArray( m_nVaoHandle );

// Enable the vertex attribute array (we're using interleaved array, since its faster)
glBindBuffer( GL_ARRAY_BUFFER,          vShaderArgs[0].nVboId );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  vShaderArgs[0].nVboIndexId );

// vertex data
for( int n = 0; n < vShaderArgs.size(); n ++ )
{
    glEnableVertexAttribArray(n);

    glVertexAttribPointer(
        n,
        vShaderArgs[n].nFieldSize,
        GL_FLOAT,
        GL_FALSE,
        vShaderArgs[n].nStride,
        (GLubyte *) NULL + vShaderArgs[n].nFieldOffset
    );

    AppLog::Ref().OutputGlErrors();
}

This doesn't render correctly at all.  I get a pattern of white specks onscreen, in the shape of the terrain rectangle, but there are no regular lines etc.  Here's the code I use for rendering:

void ShaderProgram::Draw()
{
using namespace AntiMatter;

if( ! m_nShaderProgramId || ! m_nVaoHandle )
{
    AppLog::Ref().LogMsg("ShaderProgram::Draw() Couldn't draw object, as initialization of ShaderProgram is incomplete");
    return;
}

glUseProgram( m_nShaderProgramId );
glBindVertexArray( m_nVaoHandle );
glDrawArrays( GL_TRIANGLES, 0, m_nNumTris );

glBindVertexArray(0);
glUseProgram(0);
}

Can anyone see errors or omissions in either the VAO creation code or rendering code?

thanks!


texts: Unity3d: Find which gameObject is in front

texts:
I have two gameObjects A and B. They are rotated at 90 degrees, which makes its local y axis face forward.

1st Case

In this case, the local y position of B is ahead of local y position of A

2nd Case

Even though their global position is same as the 1st case, we can observe here that local y position of A is ahead of local y position of B.

I tried using A.transform.localPosition.y and B.transform.localPosition.y to find which is greater but it doesnt work. What can I do to find which is front in these two different cases?


texts: Input.GetKey("example") ect. Player Input not working full screen Unity Engine

texts:
hopefully this is a simple fix i tried looked for others with the issue but I don't know if I am bad at google or if this is just an issue with me.

When I go into test mode to test player inputs it works if I am still in the main screens with my scene, game display, and all my toolbars and option. but when I press game and click Shift+Space to go full screen and then press play, I lose all access  to my Player Inputs. Is there something I need to enable or is it just 2 am tiredness?


texts: Is It Okay To Use Real Designs In My 2D Game? [Cars and Weapons]

texts:
I am making a 2D mobile game that includes cars and weapons (like GTA let's say). I am using real car and weapons designs to make 2D images, however, I use made-up names for the both cars and the weapons. Is it still copyrighted?

For example; Traffic Racer and Traffic Rider. In the games, the car models are exactly the same as the real ones, but there is no logo nor name in Traffic Racer. In Traffic Rider, you can clearly see BMW in the game (both the design and the logo). Because of these examples, I think, my situation should be okay since the game is not even 3D.


texts: Is there a common library for key listener for Java?

texts:
I'm making a game engine which supports Swing and JavaFX at the same time.

I provided key listener APIs like this:

Swing

fun addKeyListener(
    typed: Consumer<KeyEvent>? = null,
    pressed: Consumer<KeyEvent>? = null,
    released: Consumer<KeyEvent>? = null) {
    addKeyListener(object : KeyListener {
        override fun keyTyped(e: KeyEvent) {
            typed?.accept(e)
        }

        ... // Something similar for release and press
    })
}

fun addKeyTypedEvent(keyCode: Int, key: Consumer<KeyEvent>)
    = addKeyListener(typed = Consumer { e ->
            if (e.keyCode == keyCode) key.accept(e) })

... // Something similar for release and press

JavaFX

var onKeyTyepd: EventHandler<in KeyEvent>
    get() = scene.onKeyTyped
    set(value) {
        scene.onKeyTyped = value
    }

... // Something similar for release and press

But I want to extract an abstract common API to reduce the cost of migrating between Swing and JavaFX.
Since Swing and JavaFX uses different KeyEvent, I currently have no idea.

Is there any solution?


texts: Outputting Unity commandline build log to console?

texts:
I'm using Blue Ocean to do a Unity3D build through command lines (https://docs.unity3d.com/Manual/CommandLineArguments.html).

I currently have a stage in blue ocean which runs the build command in a 'Windows Batch Script' outputting the log to a text file on the computer.

is there a way to also output that same logging text to the blue ocean build output? Right now all I see is the batch command.

One way to accomplish this would be if the build output was sent to the console instead of just the logfile passed in the argument.


texts:
I'm making a three in line game with godot, but i'm having an issue.
First time when swapping cells, the animation of swapping and the elimination of cells (in the case of making 3 or more cell aligned in a line) played both at the same time.
So i refactored a bit the code, now i have queue for each cell that manages the animation to be played one by one.
Now my problem is this, the cells that the player swaps, they do fine, the play the swap animation then the elimination animation. the problem are the other cells in the line, those get removed as the first cells are playing the swap animation first and then elimination animation.
| *              | Step 1           | Step 2          |
| cells in line  |  remove animation|   nothing       |
| swaped cells   |  swap animation  | remove animation|

in case i didn't explained well i left a more graphic description of the flow of the animation steps.
this is how i want the animation to be played
| *              | Step 1           | Step 2            |
| cells in line  |  nothing         |   remove animation|
| swaped cells   |  swap animation  | remove animation  |

I'm not sure how to solve the problem, each cell manages their animations in the queue.


texts: How would I go about coloring marching cubes terrain?

texts:
I'm making a game with marching cubes terrain (I know very original idea) and I don't exactly know how to color it. I have a system to do it, I just need to know how to interpolate it where it's not all smoothed out.
I just want flat colors, I think it boils down to this function (this is this guys code http://www.paulbourke.net/geometry/polygonise/):
glm::vec3 VertexInterp(const float& isolevel,const glm::vec3& p1,const glm::vec3& p2, const float& valp1, const float& valp2) {
    float mu;
    glm::vec3 p;

    if (ABS(isolevel-valp1) < 0.00001)
        return(p1);
    if (ABS(isolevel-valp2) < 0.00001)
        return(p2);
    if (ABS(valp1-valp2) < 0.00001)
        return(p1);
    mu = (isolevel - valp1) / (valp2 - valp1);
    p.x = p1.x + mu * (p2.x - p1.x);
    p.y = p1.y + mu * (p2.y - p1.y);
    p.z = p1.z + mu * (p2.z - p1.z);

    return p;
}

So if anyone could help me implement a flatter or smoother variant of that function it would be very much appreciated
(I know all the rest of the things I need to do I just need help with this)


texts: Unity: Accessing method from (script_2) without hardcoding it in (script_1)

texts:
I have some custom script for enemy's AI.
Let's call it:
"firstEnemyAI.cs"

And I have "master" script called "Enemy.cs" attached to the GameObject.

Is there any way to attach "firstEnemyAI.cs" script to the "Enemy.cs" script for calling some "firstEnemyAI.cs" methods, without need to hardcoded class name of "firstEnemyAI.cs" script?

If I access it in "Enemy.cs" via

GetComponent<FirstEnemyAI>();

I will need to edit my "Enemy.cs" script every time, I want to try another AI pattern :(


texts: How to get time since frame start in Unity for loading purposes

texts:
I am building a big world (1000+ game objects). It takes 2s on the device. I am doing it in the background (the world is hidden until fully loaded). I have figured out that I can maintain the FPS of the active scene by switching to coroutines and making yield return null;.

The main issue is when to fire yield return null;. If I do it too often, then it will slow down the loading. If I do it too rarely, it will reduce FPS on low-end devices.

My idea is simple to detect how much milliseconds have passed since the start of the frame and fire yield return null; just after I have spent for example 12ms (to leave some time to render everything else and maintain something near 60FPS).

However, I can not find an efficient way of getting the time since frame start? Unity should have something as the async loading of assets seems to consume just right time to maintain stable FPS.


texts:
I am currently working on a chatbot game using Python 2.7.10.
I use the Chatterbot library.
This library seems to do all I need but the training data (or corpora) are very very limited.

I haven't quite decided what the game is going to be like.  I was thinking of doing something where the bot contacts you on behalf of a assassinated police inspector and asks you to help it solve the case.

But I am still at the stage where I am experimenting what can and can't be done using a chatbot.

An alternative to this game would be a simple "guess who" kind of game.

I had a look online expecting to find a lot of every day conversation chat logs especially made for training chat bots. But I could only find a few logs of quiet random conversion (mostly on programming). I thought of using plays and film scripts but that requires a lot of editing. What recommendations would you have.  I basically need strings lists in which each string is a response to the previous one. I can also train pairs of question answer.


texts: How can I design an effective some sort of sequence system?

texts:
I am making a story driven game right now, and I want to create a system that will allow me to code sequences easily without creating a mess from the project.
What I mean by sequences is for something like a Scene, for example, since it's story driven, the player begin in a room, which then a character walk in, display a dialogue, then walks away, does a few things, a couple of sounds and effects are played, etc.

I was wondering how I could structure a system like that, that will allow me to have hundreds of this sequences without making a big mess of my project, also, these are going to be must like scripted, is it better to keep most of the scripts in a fewer class files or it's a good idea to spread them more? (to more class files)

I hope you can understand exactly what I meant and thank you in advance.

(I am making this in C# in Unity but I am not looking for specific code, just theory how to construct such system effectively)


texts: Prevent Wall Clipping with Bouncing Shape

texts:
I'm currently working on a demo-type program involving bouncing objects. Currently, I have a rectangle that can bounce around the screen.
When the rectangle bounces against one of the walls imperfectly, part of it will clip into the side of the window (or other objects, in the future).
I'd like to have the rectangle bounce from an accurate position (as in when/where it begins to collide with the object). Is there a better or more efficient way to do this other than by going back a step and checking over again with smaller steps?

The relevant code is here, and for reference the rectangle's velocity is stored as an angle and speed.

    //Update position
    rect.setX(rect.getX() + (rect.getVelocity() * Math.cos(rect.getDirection())));
    rect.setY(rect.getY() + (rect.getVelocity() * Math.sin(rect.getDirection())));

    //Check for collisions
    for(Collider c : colliders) {
        if(c.isColliding(rect)) {
            bounce(rect, c);
            System.out.printf("Rect is colliding with %s%n", c);
        }
    }

Any help would be appreciated.


texts: Unable to rotate box2d body with torque if revolute joint introduced

texts:
I created a simple body (PLAYER) which, as speed increased the angle of the body increases slightly.  I set the torque property based on velocity, to change the body's angle, and it looks like the player is leaning forward as he runs.  Great.
I wanted to prevent my PLAYER from flipping over (when hitting other bodies), so I created a second body and placed a revolute joint between them.  The second body has rotation disabled, and is dynamic.  I discovered that I did not need to apply any angle limits to prevent flipping, since the joint seemed to resist rotation.  The player actually rights himself if flipped on his side.  (The joint seems to want to return to 0 angle). The motor is disabled, no motor speed, no motor torque.  Still, the joint returns to 0'.
The PLAYER still rotates a bit when hitting other bodies, but I can no longer rotate the body with any torque value (to make him lean forward).  Why?  I need to restore the leaning effect.
I don't understand why the second body + revolute joint prevent rotation due to any torque applied.  Can someone explain, and offer solution?


texts:
Below is a two droplet merging together,in 2d.
I want to simulate the behavior when I exert combination force(through mouse or fling force on touch screen) on one of them to
make them to be a larger droplet.
I suppose there exists some kind of function by the distance of these two droplet's center,when the distance is closer,one becomes smaller,the other one becomes larger.
What kind of model should I build? Particles or geometry circles or sth else?


texts: Creating an mouse-friendly GUI in a "sort of" Python console mode

texts:
I'm developing a real-time rogue-like game during my spare time, using Python and libtcod, to learn programming (and have some fun). I would like to create some sort of mouse-friendly GUI, just like in Goblin Camp.

This game is 90% mouse-driven, with menus, scrollbars, buttons etc.
As a total noob with graphical interfaces, I just can't figure out how to do this. Example: How to display the name of a monster when the cursor is over it? I tried some ways, which more or less worked, but were always awful, impossible to maintain, hard to scale, and resource-consuming.

Is there a "simple" way to have something more like an object.OnClick() ?


texts: Procedural generation of semi-correct planetary systems

texts:
So there are lots of resources you can find via Google or using the search here on how to procedural generate a whole galaxy. But I couldn't find any good resource on how to generate planetary systems that follow these criteria:

The systems don't have to be accurate simulations of orbits but should be close to plausible orbits. I don't care about any simulation that cares about how the system might look in 200k years, the orbits could be rock solid. The main problem I'm facing is how to randomly generate a system that could be seen as plausible. This becomes especially interesting when you have a system with a binary star.

Just randomly creating orbits won't make up a plausible system, you'll end up with obviously non working orbits. Yes, I'm aware of the N-body problem :) but this doesn't help me, at least I think so, to solve the problem of generating a plausible system procedural?

I think you could just randomly spawn planets on their orbit and give them a mass and then use the N-body mathematics to calculate if they're more or less valid, if not start over and randomly generate new orbits until you get something that matches, but this would be very inefficient.


texts: Gameobject not destroyed OnCollisionEnter

texts:
I have this GameObject with the tag coin I am trying to destroy when the player collides with it using this code located in a player script attached to the player

    public void OnCollisionEnter(Collision col){
        var hit = col.gameObject;
        if(hit.tag == "Coin"){
            Destroy(hit.gameObject);
        }
    }

However upon collision nothing is happening


texts: Setting up OpenGL on Mac OS 10.10 while keeping it cross-platform

texts:
I have experience with game programming mainly in allegro or drawing everything on native windows (No graphic libraries). Now I am interested in learning OpenGL for game development. I have found several OpenGL tutorials, but right now I only want to set up my environment so that I can be able to open windows and draw on them. I use Mac OS, but I am very interested in making all of my code as cross-platform as possible, so I would like to know how to set up (download, install, make a hello world kind of thing)  OpenGL on a mac, but preferably without using Xcode or Apple depending stuff. I already checked to see whether my mac supports newer OpenGL and it does, so I will try to use the most recent standards.

I am ok with writing makefiles to link libraries and that kind of stuff that usually Xcode does for the sake of portability.

I keep wondering if I will need to always write some platform specific code when creating a mainly cross-platform game... and my guess is I will, but I want to minimize it. Anyway, I would like to know your advice for me. I hope my question is clear, but feel free to ask any detail you might need to know.


texts: Why is the bullet not created realitive to the player?

texts:
I'm using GameMaker to make my game and I'm trying to get the player bullet to fire out of the players gun but for some reason even though I checked 'relative', the bullet is still being created at the top of the room.

Why? How could I have the bullet created relative to the player?


texts: Game Design Issue: Special items implementation

texts:
I have a Match Two game similar to the bejeweled board. I am rewarding the player on speed of score. If he scores X in Y time , he gets a bomb. The time window is not rolling but discreat.

I check what the users score was in last X seconds after every Y seconds and reward him. The issue is the reward is a bomb which explodes 9 tiles. (I've dumbed down the score of the tiles exploded by bombs) Now that score will be counted in the next user score check and if the user made of more pair he will be given another bomb and this continues.

So once the user gets a bomb it's very easy to get it again and keep getting it. Which ruins the uniquness of the bomb. If I say hey let's not count the score because of the bomb that way the user will have to start all over again to get a bomb and if we have Z types of bombs one better than the other it would be impossible for the user to get all the bombs. If the score keeps on restarting.

I'm having a hard time finding the middle ground in it. Any ideas?

Also for special items, what seems to be better roll over time windows or static time windows?


texts: Clothing and physics asset collisions not working

texts:
I"m making a character in Blender where there's a character mesh and a simple skirt.
The skirt has a different material slot, which allows me to use the Unreal Clothing tool. I created the clothing data, applied it, painted it so the top part isn't moving at all and bottom has 100 "dynamics".
I also created a physics asset, however no matter what settings I try, the skirt will always poke through the thighs like they don't exist. All the colliders are capsules. I also get the feeling that the hip collider actually works. But only that one!
The skirt works perfectly with the wind, which makes it even weirder.
Does anyone know what can cause this?


texts:
so i am making a thing in javascript and i want to have planetary gravity in my "universe".

But when i use an equation to calculate the acceleration by gravity i get one number. That is how fast the object accelerates in the direction of the other object, but how do i convert a speed in one direction to a speed in the X, Y and Z axis?


texts:
How do you make it easy for your artists to author content for an HDR renderer? What kinds of tools should you provide, and what workflows need to change, in going from LDR to HDR?

Note that I'm not asking about the technical aspects of implementing an HDR renderer, but about best practices for creating materials and lighting in HDR.  I've googled around a bit, but there doesn't seem to be much about this topic on the web.  Can anyone point me to some good resources on this, or share their own experiences?

Some specific points:

Lighting - how can lighting artists pick HDR light colors? Do they have a standard LDR color picker and then a multiplier? Is the multiplier in gamma or linear space? Maybe instead of a multiplier it's a log-luminance? Or a physical brightness level, like the number of lumens? How will they know what multiplier/luminance/brightness is "correct" for a given light?
Materials - how can texture artists make emissive color maps, such as neon signs, TV screens, skyboxes, etc? Can you paint one as a regular LDR (8-bit-per-channel) image and apply a multiplier (or log-luminance, etc.)? Are there cases where it's necessary to actually paint HDR images? If so, how do you go about this in Photoshop (or other software)?


texts: Looking for a full featured C/C++ UV Mesh Unwrapper

texts:
My first question!
Is there an open source C++/C piece of code easy to integrate to solve the UV Unwrapping of arbitrary meshes out there ?
I would like to use it to build a light mapper or similar stuff.
Of course i'm looking for non-naive solutions but something that solves the issue with maximum exploiting of texture surface and so on..

Thank you guys in advance.


texts: Why does my rendering not correspond with my Box2D world?

texts:
I've decided to try to use the Box2D physics engine in my game, and as I started I'm facing weird behaviour. I've followed a video tutorial where we setup the Box2D world with world gravity, and then create an entity containing the collider.

Here's how I'm creating the entities:

void PhysicsEntity::init(b2World* world, vec2 position, vec2 dimensions)
{
    _body = createComponent<pin::WorldComponent>(this);
    _body->initWorld(position);

    _sprite = createComponent<pin::Sprite>(this);
    _sprite->initRender(dimensions, pin::TextureManager::loadTexture("crate.png"), _body);

    //PHYSICS STUFF
    b2BodyDef bodyDef;
    bodyDef.type = b2_staticBody;
    bodyDef.position.Set(position.x, position.y);

    _physics = world->CreateBody(&bodyDef);

    //Fixture&Shape
    b2PolygonShape boxShape;
    boxShape.SetAsBox((dimensions.x) / 2.0f, (dimensions.y) / 2.0f);

    b2FixtureDef fixDef;
    fixDef.shape = &boxShape;
    fixDef.density = 10.0f;
    fixDef.friction = 0.3f;
    fixture = _physics->CreateFixture(&fixDef);
}

Here's the render function:

void PhysicsEntity::render(pin::SpriteBatch* batch)
{

    mat4 modelMatrix;
    vec3 position(_physics->GetPosition().x, _physics->GetPosition().y, 0.0f);

    modelMatrix = glm::translate(modelMatrix,position);
    modelMatrix = glm::rotate(modelMatrix, glm::radians(_physics->GetAngle()), vec3(0.0f, 0.0f, 1.0f));

    _sprite->render(batch, modelMatrix);
}

It looks like this with Box2D debug rendering turned on:

Here's a video of how it behaves.

It looks like the collider and sprites locations differ. I've read that I shouldn't use 1 pixel = 1 meter ratio, but in many tutorials it was working without problem so I'm wondering if I forgot something.

The step settings I'm using are:

_physicsWorld->Step(1.0f / 60.0f, 6, 2);

What have I missed?


texts: DirectX11, how do I manage and update multiple shader constant buffers?

texts:
Alright, I'm having a hard time grasping how constant buffers are bound to a pipeline stage and updated. I understand that DirectX11 can have up to 15 shader-constant buffers per stage and each buffer can hold up to 4096 constants. However, I don't understand whether the ID3D11Buffer COM used to interact with the constant buffers is just a mechanism (or handle) used for fill these buffer slots or if the object actually references a particular instance of buffer data that is pushed back and forth between the GPU and CPU.

I think my confusion on the topic is the cause of a problem I'm having using two different constant buffers.

Here is some example shader code.

cbuffer PerFrame : register(b0) {
    float4x4 view;
};

cbuffer PerObject : register(b1) {
    float4x4 scale;
    float4x4 rotation;
    float4x4 translation;
};

The way my code is organized, the camera will be handling updating the relevant per frame data and GameObjects will be updating their own per object data. Both classes have their own ID3D11Buffer that is used to do this (Using a hub architecture, so one GameObject class will handle the rendering of all the instanced GameObjects in the world).

The problem is I can only get one updated at a time, depending on the slot and I presume the update order one buffer gets filled while the other gets zero'd out.

This is essentially my code. Both classes use identical update logic.

static PerObjectShaderBuffer _updatedBuffer; // PerFrameShaderBuffer if Camera class
_updatedBuffer.scale       = _rScale;
_updatedBuffer.rotation    = _rRotation;
_updatedBuffer.translation = _rTranslation;
pDeviceContext->UpdateSubresource(pShaderBuffer, 0 , 0, &_updatedBuffer, 0, 0);

pDeviceContext->VSSetShader(pVShader->GetShaderPtr(), 0, 0);
pDeviceContext->PSSetShader(pPShader->GetShaderPtr(), 0, 0);
pDeviceContext->VSSetConstantBuffers(1, 1, &pShaderBuffer);
pDeviceContext->IASetVertexBuffers(0, 1, &pVertexBuffer, &vStride, &_offset );
pDeviceContext->IASetPrimitiveTopology(topologyType);
pDeviceContext->Draw(bufSize, 0);

My main questions are -

Do I need to set or bind the ShaderBuffer in order to update it with the UpdateSubresource call? (Meaning manipulate it only when it is in the pipeline) Or is it a blob of data that will be sent in with the VSSetConstantBuffer call? (Meaning the order of binding and updating data doesn't matter, I can update it in the pipeline or somehow on the cpu)
When setting or binding the buffer, do I need to reference slot 0 to update the PerFrame buffer and slot 1 to update the PerObject buffer? Could some kind of confusion with this call in my code cause all the buffers to be overwritten?
How does D3D11 know which buffer I want to update or map? Does it know from the ID3D11Buffer COM used?

Edit -

Changed the constant buffer register tags in the example above. Using (cb#) instead of (b#) was affecting the buffers from updating correctly for some reason. Not sure where I picked up the original syntax or if it's valid at all, but it appears to of been my main problem.


texts: 2D lighting causes black rings to appear

texts:
A year ago I implemented 2d lighting in XNA using sprites.
The sprites I used were created by placing a soft white photoshop brush on a transparant background.

The result was this: (lights only)

And this seemed right to me.

I returned to the subject this week to try replacing the sprites with a texture created with code and a formula:

As you can see, there is a black ring around every light.

This is the code I used for creating the textures:

int diameter = 250;
int radius = diameter / 2;

Color[] colors = new Color[diameter * diameter];

for (int y = 0; y < diameter; y++)
{
    for (int x = 0; x < diameter; x++)
    {
        Vector2 l = new Vector2(radius, radius) - new Vector2(x, y);
        float attenuation = MathHelper.Clamp(1 - Vector2.Dot(l / radius, l / radius), 0, 1);

        colors[x + y * diameter] = Color.White;
        colors[x + y * diameter].A = (byte)(attenuation * 255);
    }
}

Texture2D texture = new Texture2D(device, diameter, diameter);
texture.SetData(colors);

I got the attenuation formula from here.

Aside from that I now create the textures using code, the rest of the code has remained the same.

Where do the black rings come from, and how do I prevent them from appearing?


texts:
I am currently writing a little roguelike and wondered how Nethack/other games do the FoV of the player. I had a look at Nethacks source code, but since it's C it's pretty hard to read.

For people who don't know how it looks in nethack:

I couldn't find good resources on how to achieve this result.
Of note is that my maps are a little more complex with regards to shape and objects that block sight.

So how would I actually implement that? Map is just an array of ints.

I figure I should have flags on each cell saying if it's been discovered or not, but how to I simulate the FoV?


texts: At about how many instances would instancing become effective? DirectX dynamic buffers seem to take a little more out of the fps than an immutable one would. So obviously you wouldn't want to make a dynamic buffer for one mesh. What about two or three? I realize there's probably many variables to take into account but just to get a grasp on it?


texts: Can I add rigging bones to a model imported from Blender inside Unity?

texts: I created a model in Blender but recently I stumbled upon a video claiming that you can add rigging to a model in Unity. So instead of rigging in Blender, is it possible to do it in Unity?


texts:
I was about to start my journey on unreal engine but currently all of the tutorials we're all about blueprints in 2D games. I really want to make 2d games since I am not good at 3d (not yet). My concern is ,all their tutorials where blueprints (not really) but most of its 2d tutorials we're  made in blueprint. Is blueprint that good and powerful than C++ in 2d game developement for UE4 or this is just an advertisement for this features? I really want more power that is why I really want to use c++ in UE4,

Main purpose is for desktop and console games only. (I don't care about the mobile industry, I prefer cocos if focusing on mobile).


texts: Why does my terrain texture fail to load? (OpenGL)

texts:
I'm currently using a vertex shader and a fragment shader for loading my texture onto the terrain I made.

Here is my vertex shader

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

float scale = 0.5;

out vec2 TexX;
out vec2 TexY;
out vec2 TexZ;
out vec3 blend_weights;

void main()
{
    vec3 blend_weights = abs(aNormal.xyz);
    blend_weights = (blend_weights - 0.2) * 0.7;
    blend_weights = max(blend_weights, 0);
    blend_weights /= (blend_weights.x + blend_weights.y + blend_weights.z);

    TexX = aPos.yz * scale;
    TexY = aPos.zx * scale;
    TexZ = aPos.xy * scale;

    gl_Position = projection * view * model * vec4(aPos, 1.0);
}

And here is my fragment shader.

#version 330 core
out vec4 FragColor;

uniform sampler2D terrainTexture;

in vec2 TexX;
in vec2 TexY;
in vec2 TexZ;

in vec3 blend_weights;

void main()
{
    FragColor = texture(terrainTexture, TexX)*blend_weights.x + texture(terrainTexture, TexY)*blend_weights.y + texture(terrainTexture, TexZ)*blend_weights.z;
}

I was trying to implement 3D texture planar projections, based on section 1.5 of this link
https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch01.html

If I just try to implement the texture in a very simple way, it works (which looks terribly stretched on the mountanous terrains, of course). But if I implement it this way, the texture does not load. What could be the possible reason?

Just in case anyone is wondering, the following is my VAO, VBO, EBO configuration

// VAO, VBO configuration
    unsigned int VAO, VBO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, positions.size()*sizeof(glm::vec3) + normals.size() * sizeof(glm::vec3) , NULL, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, positions.size() * sizeof(glm::vec3), &positions[0]);
    glBufferSubData(GL_ARRAY_BUFFER, positions.size() * sizeof(glm::vec3), normals.size() * sizeof(glm::vec3), &normals[0]);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), &indices[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)(positions.size() * sizeof(glm::vec3)));

This is my draw function

// Inside the render loop
void drawScene(Shader &shader, unsigned int VAO, unsigned int numIndices, unsigned int texture1)    //draw the scene with the parameter data.
{
    glm::mat4 model;
    model = glm::translate(model, glm::vec3(-(int)(gridXNum)/2, 0.0f, -(int)(gridZNum)/2));
    glm::mat4 view = camera.GetViewMatrix();
    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);

    shader.use();
    shader.setMat4("model", model);
    shader.setMat4("view", view);
    shader.setMat4("projection", projection);
    shader.setFloat("TERRAIN_WIDTH",gridXNum);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture1);

    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLE_STRIP, numIndices, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

However, I really don't think this is the problem because as I said, if I change the shader codes into a really basic one, the texture successfully loads. There is definitely something wrong with my shader program. Any help would be appreciated. Thanks in advance!


texts: How to rotate camera centered around the camera's position?

texts:
Currently I am using gluLook at like so:

gluLookAt(position.x, position.y, position.z,
          viewPoint.x, viewPoint.y, viewPoint.z,
          upVector.x, upVector.y, upVector.z);

with the above, don't know if you need more information, how could I change it so that the camera acts like its rotating around itself, instead rotating around its viewpoint. You can see the current code at https://github.com/dchhetri/OpenGL-City/blob/master/opengl_camera.cpp, that class was adapted from codecolony.com.


texts:
I've been recently trying to get into Object Oriented Programming by porting a game I've made in C to C++. The problem is, even though my implementation works, I don't know if is the best approach.

The game is a tower defense, which contain 3 main elements: Tiles, Enemies and Towers. Each of the three elements have a "engine" class, which manipulates and allocates the individual objects. For example:

Tiles:

Class Tile
{
  private:
  int  posX, posY;
  bool visible;

  public:
  void DrawItself();

};

Class TileEngine
{
  private:
  Tile tileArray[m][n];

  public:
  int GetTileXPosition(int m, int n);
  int GetTileYPosition(int m, int n);
  void DrawArray();
};

Enemies:

Class Enemy
{
  private:
  int  posX, posY;
  bool health;

  public:
  void DrawItself();
  void MoveItself();

};

Class EnemyEngine
{
  private:
  Enemy enemyArray[m][n]

  public:
  void DrawArray();
  void MoveArray();
};

TileEngine and EnemyEngine are then instantiated on a Game class, and their public methods are then called on a loop:

Loop()
{
  TileEngine TileEngine;
  EnemyEngine EnemyEngine;
  /*FPS controlling routine omitted*/
  while(1)
  {
    EnemyEngine.Movement();

    TileEngine.DrawArray();
    EnemyEngine.DrawArray()
  }

}

The problem is that the EnemyEngine.Movement() method requires information from the TileArray, of which it doesn't have access. My temporary solution has been giving the EnemyEngine class a pointer to the TileEngine class:

void Loop()
{
  TileEngine TileEngine;
  EnemyEngine EnemyEngine;

  EnemyEngine.pTileEngine = &TileEngine;

  while(1)
  {
    /*...*/
  }

}

But doesn't that defeat the purpose of object oriented programming?
Is there a better approach to get information between the "engine" classes? Or is the Element -> ElementEngine -> Gameloop implementation flawed altogether?


texts: How to find the Y coordinate of a line moving up and down with given specific X coordinate?

texts:
I start with a horizontal line and I run midpoint displacement algorithm to generate some mountains, then I want to place some pillars on top of the mountain by randomly choosing the X coordinate, but I need the Y coordinate of the mountain so I can place the pillar, right?

Now the idea is that these mountains will keep changing and moving, some chunks might move up or down while moving left or down, at a constant motion.

Let's say I want to place a pillar on the mountain, so I get some X coord.
How do I find the height of the mountain ledge that keeps moving?


texts: Tips on building a real time multi player web platform + framework and/or tookit

texts:
I'm trying to develop a multi player game web app which basically should be able to achieve the following goals:

Provide a game engine + framework/toolkit to let third party corporation integrate their own developed games.
Games must run realtime and multiplayer.

So the idea is to develop some kind of framework or toolkit to easily accomplish above goals.

As long as I don't want to reinvent the wheel and I need to validate each client action, and while following the premises below, I would like to know your opinion:

Web app is going to be developed using PHP language.
Clients connections are going to be managed through socket.io.js
Server validations will run on Node.js
I need to adopt a game engine that can run on top in order to let third party develop their custom games, which one?

As I'm no expert I'm looking some kind of advice or feedback based on your experience and also to let me know if I'm going in the right direction.


texts: How can I handle scripting-like tasks in my ECS?

texts:
So I have been getting more and more into ECS architecture, and I am having a bit of trouble wrapping my head around how to handle custom actions/callbacks.

For instance, let’s say I want to have a concept of a button in my game.  One button opens a door.  Another button drains the water out  of a room.  Another button opens a door, and deactivates all the cameras on this level.

With a data-driven ECS, I am struggling to figure out how one would handle this kind of diverse, specific behavior short of writing a massive enum with a case for each specific action.

My ECS is a pure data-driven one: entities are indexes to components, components are just data, and systems are implicit: they are just anything which operates on entities/components.


texts: Determining and culling non-visible vertices

texts:
Ahoy!

After posting my previous question on tile maps, i've been tinkering with an implementation i'm rather pleased with so far but would like to gather some more information about submitting geometry to be rendered by OpenGL.

A little background information:

I've set up a tile map which renders "volumes" in a layered manner very much like Minecraft's implementation using voxels (note; i'm not creating another bloody minecraft clone!) but with a twist in that any "volume" can be extruded along the Y-axis to create variably sized tiles. This all works fine and for the purposes of my tile map, is exactly what I set out to achieve.

My question:

My current confusion lies within the realms of how the vertex data is submitted to be rendered. I'm conscious that when two volumes are rendered in a single tile (think of them as layers; rock on the bottom, mud or water on top), the bottom volume is not actually visible unless there are no neighbouring tiles. To this end, is there any point in submitting the vertices for an object that may not be visible?

Consider two cuboids side by side. From any angle, you can only ever see 5 faces of each cuboid as the other faces are adjacent. Does OpenGL recognise this and discard them (if glCullFace or another appropriate method is used/enabled?) or do I need to actually determine what is visible and remove redundant vertices myself? Is there any harm in not removing them?

For the purposes of my tile map, I don't imagine that my "world" will ever be large enough to cause issues with rendering speed but I'd would like to optimise this so non-visible volumes are simply not rendered. I've been toying with a few ideas for determining which volumes are visible before adding them to the VBO but was wondering how much leg work OpenGL would do for me. There's no point me trying to solve a problem that doesn't exist and also, would OpenGL be able to calculate this much quicker that my own implementation?

I'd like the tile map to be deformable whereby the top-most volumes can be removed or resized to reveal the volumes below (also, some tiles may be transparent, such as water) so rendering the whole tile map (or at least what is visible on screen) would seem necessary.

I have the implementation down and working so far and it's running at a reasonable speed without any issues. I'm just not sure how much work OpenGL does in the background with regards to rendering and culling vertex data that isn't actually visible due to it being obscured by other objects. Can anyone provide insight into this, or at least point me in the direction of where I can read up on such matters?

Any help and information would be greatly appreciated :)


texts: Zooming and panning a camera simultaneously causes a swooping effect

texts:
In a 2d game, I have a basic camera class.  The guts of the class creates a transformation matrix that is later passed to the Begin() method of a SpriteBatch.  The transformation is done like this:

        Transform = Matrix.Identity *
                    Matrix.CreateTranslation(-Position.X, -Position.Y, 0) *
                    Matrix.CreateScale(new Vector3(Scale, Scale, Scale)) *
                    Matrix.CreateTranslation(ScreenCenter.X, ScreenCenter.Y, 0);

I'm trying to create an effect that zooms in on a specific point on the screen.  The issue is that the zoom/translation causes a strange "swooping" effect when applied.  For example, when the zoom is set to 1.0 and the current position is (0, 0), and I change these to 2.0 and (100, 200) over a 1 second interval, the camera appears to take a curved path to (100, 200).

Here is my code to update the position / scale on each frame (I removed logic to determine when the transition is finished):

        _positionTimeElapsed += gameTime.ElapsedGameTime.TotalMilliseconds;
        _scaleTimeElapsed += gameTime.ElapsedGameTime.TotalMilliseconds;

        Position = Vector2.Lerp(
            _positionStart,
            PositionDestination.Value,
            (float)(_positionTimeElapsed / TransitionTimeMilliseconds));

        Scale = (ScaleDestination.Value - _scaleStart)
             * (float)(_scaleTimeElapsed / TransitionTimeMilliseconds)
             + _scaleStart;

I'm relatively confident that I'm missing something basic about Matrix math.  Does anyone know how to transition both position and scale simultaneously and have the camera appear to take a linear path to the destination?

UPDATE

Added two videos on YouTube that show the issue and the fix in action.  These videos zoom to 10x over 5 seconds to make the bug obvious.

Broken: http://www.youtube.com/watch?v=d8fJ4Zf-sqU

Fixed: http://www.youtube.com/watch?v=GpcUc25eZ8o


texts:
I am currently making a multiplayer game however only the host has the capability to spawn projectiles.

[Command]
void CmdSpawnEgg()
{
    if (cam == null)
    {
        return;
    }
    GameObject instance = Instantiate(eggPrefab, transform.position + (transform.forward * offset), cam.rotation);
    NetworkServer.Spawn(instance);
}

//cam is the transform of the players camera and if its not the local player the camera is destroyed

The projectile is also a registered spawn-able prefab for the network manager


texts: Help understanding Unity Profiler time in ms

texts:
I'm a little confused about this column shown in the picture above.

When it shows 0.22 does it mean "22 miliseconds" or does it mean a fraction of a milisecond (i.e. in this case, around 1/5 of a milisecond) ?


texts: I have 240 prefabs to scatter, what is the best way to achieve this?

texts:
I'm creating a huge city for which I've made 240 different building prefabs. Now I need to scatter those prefabs randomly with a height, width and depth and rotation randomness variation.
I thought the prefab scatter tool provided by the polybrush package was perfect for the job, but as soon as I added more than 50 prefabs to the prefab palette, it started to glitch and act weird. The variation settings also seem to be uniquely saved  for each prefab, but I'd like to have 1 set of settings for all prefabs.
These points make me believe polybrush wan't made for scattering  a large amount of prefabs (unless I'm missing something?)
Are there any other tools that can assist me with this?
Thanks in advance.


texts:
EDIT: I forgot to mention that in this implementation E stands for Entity which is just an ID, C => Component as data-only types and S for Systems which should implement logic

Currently i'm working on a small hobby project which is a multiplayer card game with a client/server architecture. I'm using a framework for the network part which triggers message events to services objects like this:

class AuthRequestMessage : public fqpnet::IMessage
{
public:
  //methods for serialization

  inline const std::string& getLoginId() const
  { return loginId_; }

  inline const std::string& getPassword() const
  { return loginId_; }

private:
  std::string loginId_;
  std::string password_;
};

//Handles authentication
class GatewayService : public fqpnet::Service
{
public:
  //registers handlers
  GatewayService()

private:
  void onAuthRequestMessage(const AuthRequestMessage* msg, ClientSession* session);
};

and now i'm at the point where i have to create the player entity. My first thought was to create the player entity directly in the message handler. But it feels like this code should be in a system so i created a system and added a method:

class PlayerSystem : public entityx::System<PlayerSystem>
{
public:
//Entity createPlayer(/*info needed...*/);

//update etc
};

But this feels rather bad too as the method is only used once in the handler.
My third attempt was to use the builtin messaging system of the ECS:

struct PlayerAuthRequest
{
//id etc
};

class PlayerSystem : public entityx::System<PlayerSystem>
{
public:
void receive(const PlayerAuthRequest& request);

};

//and now just emit the event in the message handler
void GatewayService::onAuthRequestMessage(const AuthRequestMessage* msg,
ClientSession* session)
{
  //verify, load from db etc.
  eventMgr->emit<PlayerAuthRequest>(/*data*/);
}

Which of these approaches would be the best? Or are there alternative ones? Basicly i just want to do it in the right way to learn. Performance does not really matter to me.


texts:
I'm getting latency issues in bandwidth intensive level transitions part of my game that are proportional to the distance to the server. I believe I'm hitting TCP Slow Start issues. It's also fine when I spam level transitions in quick succession but the problems re-appears. Note that I'm not breaking the TCP connection.

Effectively the transfer rate of my game is very bursty and remote users are experiencing a high latency (0.8 second) during these events. Some of the data I need to send during these bursts are dynamic so I can't pre-exchange it.

Is there anything I can do to mitigate the problem? Sending dummy data to keep the TCP window size is pretty much not a solution.

All the data needs to be received in-order so UDP isn't really appropriate here.


texts: How to convert mouse coordinates to isometric indexes?

texts:
I draw isometric map with tile 64x32:

const Offset = 160;
int X, Y;

for (int a=0; a < 6; a++)
  for (int b=0; b < 6; b++) {
    X = a * 32 - b * 32 + Offset;
    Y = a * 16 + b * 16;
    DrawTile(X, Y, tile);
  }

Image, illustrating this code:

Dear professionals, please, help with a formula of transformation of mouse coordinates in isometric indexes of a cell. Example: (105; 100) -> [1; 4].


texts: How to detect if a ball will collide with another, and the normal vector of the collision?

texts:
So I have a 2D game involving balls (circles) colliding. I want to be able to detect if two balls will collide before it happens, and the normal vector of the collision if a collision is going to happen. Take a look at the below picture:

Essentially a normalized vector represented by the red arrow is what I am interested in knowing. How can I figure that out any frame most efficiently, given I know the following:

The blue ball has a current initial velocity
The ball ball is pulled down by a constant gravity
The green ball does not move
The sizes and location of both balls


texts: IndexOutOfRangeException on World.Step after enabling/disabling a Farseer physics body?

texts:
Earlier, I posted a question asking how to swap fixtures on the fly in a 2D side-scroller using Farseer Physics Engine. The ultimate goal being that the player's physical body changes when the player is in different states (I.e. standing, walking, jumping, etc). After reading this answer, I changed my approach to the following:

Create a physical body for each state when the player is loaded
Save those bodies and their corresponding states in parallel lists
Swap those physical bodies out when the player state changes (which causes an exception, see below)

The following is my function to change states and swap physical bodies:

new protected void SetState(object nState)
{
    //If mBody == null, the player is being loaded for the first time
    if (mBody == null)
    {
        mBody = mBodies[mStates.IndexOf(nState)];
        mBody.Enabled = true;
    }
    else
    {
        //Get the body for the given state
        Body nBody = mBodies[mStates.IndexOf(nState)];

        //Enable the new body
        nBody.Enabled = true;

        //Disable the current body
        mBody.Enabled = false;

        //Copy the current body's attributes to the new one
        nBody.SetTransform(mBody.Position, mBody.Rotation);
        nBody.LinearVelocity = mBody.LinearVelocity;
        nBody.AngularVelocity = mBody.AngularVelocity;

        mBody = nBody;
    }

    base.SetState(nState);
}

Using the above method causes an IndexOutOfRangeException when calling World.Step:

mWorld.Step(Math.Min((float)nGameTime.ElapsedGameTime.TotalSeconds, (1f / 30f)));

I found that the problem is related to changing the .Enabled setting on a body. I tried the above function without setting .Enabled, and there was no error thrown. Turning on the debug views, I saw that the bodies were updating positions/rotations/etc properly when the state was changes, but since they were all enabled, they were just colliding wildly with each other.

Does Enabling/Disabling a body remove it from the world's body list, which then causes the error because the list is shorter than expected?

Update:

For such a straightforward issue, I feel this question has not received enough attention.  Has anyone else experienced this? Would anyone try a quick test case? I know this issue can be sidestepped - I.e. by not disabling a body during the simulation - but it seems strange that this issue would exist in the first place, especially when I see no mention of it in the documentation for farseer or box2d. I can't find any cases of the issue online where things are more or less kosher, like in my case. Any leads on this would be helpful.


texts:
I'm trying to implement negamax in my checkers game. Sometimes the IA does the appropriate move, sometimes don't. Here is my code:

private int evalPawns(ArrayList<Pawn> pawns, int turn){
    int whiteCount=0;
    int blackCount=0;
    int who2move;
    if(turn == GameData.PLAYER1)
        who2move = -1;
    else
        who2move = 1;
    for(Pawn pawn:pawns){
        if(pawn.getPlayer() == GameData.PLAYER1){
            whiteCount++;
        } else {
            blackCount++;
        }
    }
    return  (whiteCount-blackCount) * who2move;
}

public int negaMax(ArrayList<Pawn> pawns, int depth, int turn){
    ArrayList<Pawn> pawnTemp;
    pawnTemp = copyPawns(pawns);

    Move[] legalMoves = getLegalMoves(turn, pawnTemp);
    int maxScore = Integer.MIN_VALUE;

    if(depth == 0 || legalMoves == null)
        return evalPawns(pawns, turn);

    for(Move move:legalMoves){
        makeMove(move, pawnTemp);
        int score = -negaMax(pawnTemp, depth-1, opponent(turn));
        maxScore = Math.max(maxScore, score);
    }
    return maxScore;
}

public Move findMaxMove(Move[] legalMoves, ArrayList<Pawn> pawns){
    int maxScore = Integer.MIN_VALUE;
    Move bestMove = null;
    for (Move move:legalMoves){

        makeMove(move);

        int newScore = -negaMax(pawns, 5, GameData.PLAYER2);
        if (newScore > maxScore){
            maxScore = newScore;

            bestMove = element;
        }

    }
    return bestMove;
}

Here are 2 moves examples:


texts: How to choose a success and failure sound

texts:
I create a math game where the user has to solve an equation. If the user is right, the application plays sound A. If he's wrong, it plays sound B.

What criteria should I use to choose sounds for A and B?


texts: Unity - How to keep an object at the right or left of another object

texts:
I created a WallCheckRight and a WallCheckLeft linked to my character.
However, I noticed that when my character do a flip, they switch place (right to left and left to right)

Is there any way to prevent that?


texts: *Python* Class - self.x = self - What does it mean to set it to self?

texts:
I have this class for my game that is a scene manager. I followed a tutorial and I am confused on why the self.scene.manager is equal to self

class SceneManager(object):
    def __init__(self):
        self.go_to(TitleScene())

    def go_to(self, scene):
        self.scene = scene
        self.scene.manager = self #<--

In the main game scene I also have a similar thing happening

class GameScene(Scene):
    def __init__(self, levelno):
        super(GameScene, self).__init__()
        self.player = Player(5, 40)
        self.player.scene = self

What is the purpose of setting it to self?

Another Question:
I have been using classes and for most of them I create a class and I include this within the class

Class myClass():
   super(myClass, self).__init__() #<----- This line here

Does this have something to do with my original question?
What is the purpose of doing this?


texts: Hinge/Configurable Joint rotating even if constrained

texts:
I already posted the question over on Unity forums, though, I have to say, this place often seems more professional and knowledgable, so here goes mirror post.

I have a Cylinder with a Hinge and a Pole that is attached to the Hinge. The Hinge axis is is set to Y, due to Cylinder being flipped for it to be rollable.

This is the order in Hierarchy:

(I've given various attempts, hence the descriptive name.)

The rigidbodies — left one for Cylinder, the right one for Pole:

As can be seen, the Pole is set to Freeze Rotation on X.

And, the Hinge:

Nothing overly special, also, as per HingeJoint documentation, I had attempted to "Disable Preprocessing" to no avail.

The problem is that even though the Pole is set to not rotate around X, it still does. For instance here, when the Cylinder has rolled all the way to it's stopping point, the Pole slowly rotates:

Full video of the roll can be seen here: gifv @ imgur.

I have also attempted to recreate the Hinge with Configurable Joint, didn't help either.

How do I stop this rotation? I need the Pole to mimic the roller Cylinder, just excluding the X rotation.


texts: how to generate mipmap, and check if done properly?

texts:
i am implementing Mipmapping for my texture for the first time.

i have 2 questions

HOW TO CHECK IF MIPMAP IS DONE PROPERLY ?
HOW TO SET MIPMAP FOR TEXTURE FROM FILE ?

First one. i implemented texture in application.

ID3D11Texture2D* TEX;
D3D11_TEXTURE2D_DESC DESC;
DESC.ArraySize = 1;
DESC.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
DESC.CPUAccessFlags = 0;
DESC.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
DESC.Width = 256;
DESC.Height = 256;
DESC.MipLevels = 9;
DESC.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
DESC.SampleDesc.Count = 1;
DESC.SampleDesc.Quality = 0;
DESC.Usage = D3D11_USAGE_DEFAULT;
r_assert(graphic->Device()->CreateTexture2D(&DESC, nullptr, &TEX));
ID3D11ShaderResourceView* TEXV;
D3D11_SHADER_RESOURCE_VIEW_DESC TEXVDESC;
TEXVDESC.Format = DESC.Format;
TEXVDESC.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
TEXVDESC.Texture2D.MipLevels = -1;
TEXVDESC.Texture2D.MostDetailedMip = 0;
r_assert(graphic->Device()->CreateShaderResourceView(TEX, &TEXVDESC, &TEXV));
graphic->DContext()->GenerateMips(TEXV);
D3D11_TEXTURE2D_DESC desc;
TEX->GetDesc(&desc);

not sure, but i think i generate Mipmap for TEX
and i just want to know the ways how to check/debug if mipmap actually done well.

Second.
i am also using DirectX::CreateWICTextureFromFileEx to create texture from file.

resource=nullptr;
newSRV=nullptr;

r_assert(
    DirectX::CreateWICTextureFromFileEx(
        graphic->Device(),
        (L"Data\\Texture\\" + fileName).c_str(),
        0,
        D3D11_USAGE_DEFAULT,
        D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
        0,
        D3D11_RESOURCE_MISC_GENERATE_MIPS,
        DirectX::WIC_LOADER_DEFAULT,
        &resource,
        &newSRV)
);
graphic->DContext()->GenerateMips(newSRV);
ID3D11Texture2D* tex = nullptr;
r_assert(
    resource->QueryInterface(IID_ID3D11Texture2D, (void**)&tex)
);
D3D11_TEXTURE2D_DESC desc;
tex->GetDesc(&desc);

and i checked desc.MipLevels is 1, which means there is no mipmapping.
so wonder how to generate mipmap when using WIC function?

any advice would be appreciated^


texts:
So using LibGDX accelerometer methods, I'm able to get the rotation of the device in the X and Z axes in degrees with this code:

 @Override
public void render(float delta) {
    float accX = Gdx.input.getAccelerometerX(),
            accY = Gdx.input.getAccelerometerY(),
            accZ = Gdx.input.getAccelerometerZ();

    float moduleValue = (float) Math.sqrt(accX * accX + accY * accY + accZ * accZ);

    //Here I do the gravity compensation
    accX /= moduleValue;
    accY /= moduleValue;
    accZ /= moduleValue;

    float xRotation = (float) Math.atan2(accY, accZ) * MathUtils.radiansToDegrees,
            zRotation = (float) Math.atan2(accY, accX) * MathUtils.radiansToDegrees;}

However, get the rotation in the Y axis is not that easy to obtain, and if I try to get it by this way, it returns erroneus values.


texts: How can I use a Texture2D larger than 2048 x 2048?

texts:
I'm having issues working with a large image.  I've read other threads on using images larger than a Texture2D supports, but found nothing that addresses my problem specifically with implementation hints.

My screen resolution is 1920 x 1080.  I'm working in C# XNA.  The game in question is pretty much a board game.

I have an 3840 x 3840 image I planned to use for the terrain map.  The idea was to make each new game look a little different from the last by having the program randomly select a 1920 x 1080 segment of that large image to display.  My code to randomly select and display a part of the image is working.

Unfortunately, I can't even get the initial 3840 x 3840 image to load.  Just picking "Add Existing Item" and adding the image to the content window on the right causes my program to error that a Texture2D can only be 2048 x 2048 maximum.

How do I best handle this?  I may later need to scale or rotate the map.

Suggestions I've seen around:

Cut it up into sections.
Use a smaller image that is made "seamless" or "tile-able", then choose a random starting X,Y point in it and fill the screen with that.

Are these good ways to go about it? How would I actually do this? Would I still be able to scale and rotate the map?


texts: Normal to an edge of a polygon, from a point inside the polygon

texts:
Suppose that I have a closed boundary that is represented by n points. Using these n points I construct a polygon with n sides. I have a point P(x,y) that lays inside the polygon.

I want to draw the normal from Point P to the edge/edges of polygon. Depending on the shape of the polygon, I can have multiple edges to which I can draw normals from point P. How shall I select the subset of edges (from all edges of polygon) that can be chosen to draw normal from point P?


texts:
I'm just starting with XNA and I wanted to draw Debug Lines around my Texture/Sprite to help me.

Is there an easy way to do it with SpriteBatch?
I haven't used the GraphicsDevice yet to draw....

Thanks!


texts: How do I edit a Texture2D at run-time to visually indicate connected tiles?

texts:
I'm making a 2D sandbox game in C# and MonoGame, and I have a couple of tile sprites. These tile are loaded in-game as Texture2Ds. I want to have blocks visually connect to adjacent blocks.

An example:

This is how a tile would look if it was connected to another tile to its right side:

Here's if all of its sides were connected:

If none of its sides were connected at all:

I think you see the idea. Starbound and Terraria do a similar thing.

I don't want to have like 10 different textures for each block for every combination of every side, as that needlessly takes up space.

What can I do in the code to edit my existing sprites to look like this? Am I just better off going with 10 different textures? Or maybe there's something better I've missed?


texts: Idle/Clicker games, supporting numbers many factors bigger than trillions in C# using Unity

texts:
Apologies for sloppy work and probably a poor grasp of fundamentals.

I have a (likely primitive) way to convert the ever increasing number values of my enemy hp into a string format to display in game. (K for thousands, M for millions, B for billions etc)

 if (target_healthmax >= 1000)
     {
         if (target_healthmax >= 1000000000)
         {
             enemy_hp_text.text = "Health: " + (target_healthcur * 0.000000001f).ToString("#.00") + "/" + (target_healthmax * 0.000000001f).ToString("#.00") + "B";
         }
         else
         {

             if (target_healthmax >= 1000000)
             {
                 enemy_hp_text.text = "Health: " + (target_healthcur * 0.000001f).ToString("#.00") + "/" + (target_healthmax * 0.000001f).ToString("#.00") + "M";
             }
             else
             {
                 enemy_hp_text.text = "Health: " + (target_healthcur * 0.001f).ToString("#.00") + "/" + (target_healthmax * 0.001f).ToString("#.00") + "K";
             }
         }
     }
     else
     {
         enemy_hp_text.text = "Health: " + target_healthcur + "/" + target_healthmax;
     }

but I stopped here after I noticed that although I could convert long numbers I would eventually hit a number too large to handle such as "-2.147484e+09" in my editor, and it would stop working.

I am using floats currently, is there a different type of variable that handles this easily? if not, what is an efficient way of solving this?

Would it be efficient to convert every new factor of 100 to a new variable and only handle the highest valued variable?
eg

if num >= 1000, k += 1, num = 0;

 if k>= 1000, m += 1, k = 0;
 ...

(Please feel free to let me know anything about my post I may need to amend, I am new here)


texts: What can I do about a "missing mcp.cfg" error?

texts:
I am trying to use MCP. After trying to run decompile.sh, I manually ran decompile.py, getting the error "ERROR:root:!! Missing mcp.cfg !!"

I tried to copy the variables from mcp.cfg into the files which reference them, but I still got the error. How can I fix this?


texts: How do I connect different parts on Blender?

texts:
I'm new to blender, trying to make my first model. I've got a body, a shoulder, an arm and a head - all separated. How do I connect them correctly?

shapes http://dl.dropbox.com/u/62862049/Screenshots/fr.png


texts:
I am currently developing car game in AndEngine. In which I was using revolute joint for car wheel and chassis attachment. But my friend suggest me that use wheel joint for that purpose for better behavior of the car. In AndEnginen I didn't found the wheel joint implementation. So what I have to do for wheel joint implementation.

I think I have to manually update the box2d library for this purpose but I don't know how many things get updated. Please suggest me some guidance on achieving better car behavior in AndEngine.


texts:
All of my quads appear correctly textured on the Unity3D editor, a Motorola Xoom Android tablet, and on an iPad 2:

But on our Samsung Galaxy Mini 2 smartphone they kinda look like this:

I wrote a debug shader that outputs the texture coordinates U and V to the R and G channels respectively, and results were consistent:

What could be causing this difference between devices?


texts: How are vertex shader outs sent as inputs to the fragment shader?

texts:
I'm learning some OpenGL 3.2 way of doing things and I think it's quite great, I'm actually understanding more of shaders and non-fixed pipeline in 1 week rather than those 2 years I tried to learn OpenGL fixed pipeline functions. But here's my question:

From what I think I've understood the vertex shader is run for each vertexes in the VBO. But the fragments shader is run per each pixel (is that right?) which is a huge number compared to let's say 3 vertexes of a triangle.

Now it seems that in the vertex shader the out variables (like colors and stuff) are passed 1 to 1 to the fragment shader. But let's say that I pass to the fragment shader the position of the vertex in the vertex shader. How is all executed? What vertex (A, B or C of the hipothetical triangle) is passed per each fragment and why?


texts: Get derived Pawn from collision actor in UE4

texts:
I am trying to build a basic RTS unit selection but any time I try to possess the target pawn it crashes.

The pawn in the collision is a blueprint derived directly from APawn.

Am I casting from the actor incorrectly?

How do i correctly get a pointer to my target unit from a collision?

void A_test_PlayerController::Input(FHitResult HitResult)
{

    // hit something
    if (HitResult.bBlockingHit)
    {
        AActor* hitActor = HitResult.GetActor();
        APawn* hitPawn = Cast<APawn>(hitActor);

        // hit a pawn
        if (hitPawn != nullptr)
        {
            // pawn is not currently controlled
            if (!hitPawn->IsControlled())
            {
                Possess(hitPawn); // <- crashes here!
                // selected new pawn
            }
            else
            {
                // pawn is already controlled
            }
        }
        else
        {
            // did not hit any pawns
        }

    }

}

Edit: found this, seems i might be doing it the right way, but it still crashes..
https://answers.unrealengine.com/questions/59297/line-trace-not-recognizing-actor.html


texts:
How would I go about making certain tiles in my array collide with my player? Like say I want every number 2 in the array to collide. I am reading my array from a txt file if that matters and I am using the slick2d library.

Here is my code if needed.

public class Tiles {

Image[] tiles = new Image[3];

int[][] map = new int[500][500];

Image grass, dirt, mound;

SpriteSheet tileSheet;

int tileWidth = 32;
int tileHeight = 32;

public void init() throws IOException, SlickException {
    tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight);

    grass = tileSheet.getSprite(0, 0);
    dirt = tileSheet.getSprite(7, 7);
    mound = tileSheet.getSprite(2, 6);
    tiles[0] = grass;
    tiles[1] = dirt;
    tiles[2] = mound;

    int x=0, y=0;
BufferedReader in = new BufferedReader(new FileReader("assets/map.txt"));
String line;
while ((line = in.readLine()) != null) {
        String[] values = line.split(",");
    for (String str : values) {
            int str_int = Integer.parseInt(str);
            map[x][y]=str_int;
            //System.out.print(map[x][y] + " ");
            y=y+1;
        }
//System.out.println("");
x=x+1;
    y = 0;
}
    in.close();
}

public void update() {

}

public void render(GameContainer gc) {
    for(int x = 0; x < 50; x++) {
        for(int y = 0; y < 50; y ++) {
            int textureIndex = map[y][x];
            Image texture = tiles[textureIndex];
            texture.draw(x*tileWidth,y*tileHeight);
        }
    }
}

}

Edit - Solved

public boolean collision() {
    playerRect = new Rectangle(x,y, playerWidth, playerHeight);

    for(int i = 0; i < tiles.map.length; i++) {
        for(int j = 0; j < tiles.map.length; j++) {
            if(tiles.map[j][i] == 2 || tiles.map[j][i] == 3) {
                tileRect = new Rectangle(i*tiles.tileWidth, j*tiles.tileHeight, tiles.tileWidth,tiles.tileHeight);
                rect.add(tileRect);
            }
        }
    }
    for(Rectangle collision : rect) {
        if(collision.intersects(playerRect)) {
            return true;
        }
    }
    return false;
}


texts: How do I make voting to kick a "leader" player fair?

texts:
My game has many rooms of around 10 people where they compete. It's basically one big guy against the other small 9 people.

However, sometimes the one guy will intentionally 'troll' and make for an unfun game for the other 9 people. These people would like to kick the one guy to replace him with one of the other 9.

If the vote was required to be unanimous (other than the guy being kicked), then him just having one friend in the game would prevent the vote from passing. Likewise, if you did unanimous minus one, then two friends could stop the vote, etc.

There there is the issue with small rooms. If a room has only two or three people, then one guy can trivially kick other people.

Has any research been done for optimal votes required to kick someone from a room depending on how many people are in the room?


texts: Find vector tangent to circle through a point

texts:
C2 and P1 are known points. Radius of circle C2 is also constant and known. I am trying to find point T to eventually construct line p1-t, which is tangent to circle c2.

I have made an attempt involving bisecting c2-p1 at M, and performing trigonometric operations to find measure of angle TMC2. Then, I found the difference in x and y coordinates from m.x and m.y using a polar form to cartesian (polar: angle tmc2 and length of tm = c2m = 1/2 c2P). After this, I normalized vectors c2P and added the difference in x, normalized the vector perpendicular to c2p and added the difference in y.

This approach seems very convoluted for such a simple task. Are there any basic vector operations to save time and processing power?

Thank you


texts: Cannot open a package from the Unity Asset Store website

texts:
Yesterday I found an asset on the Unity Asset Store website, clicked the button "Open in Unity", and it was opened in Unity.

Today, when I did the same thing, I got the error message below:

I opened the Defaults Apps page in Windows 10 Settings. But what do I do from here?


texts: Will using shaders or some other way of talking directly to the GPU always be faster than drawing to the screen in whatever language a game is being (mainly) written in? I guess that code with lots of conditionals is slower on many, (most? all?) GPUs but is that the only heuristic that can be reasonably applied? I understand that there will be edge cases with different hardware and measuring is the only way to know for sure, but I'm trying to figure out whether I should do everything that looks feasible to do in a shader, in a shader, given I don't want to implement it twice to find out which is faster.


texts: Use client as server in client/server architecture

texts:
Let me clarify what i mean by that.

Let's say i want to create a multiplayer game which uses physics (box2d).
If I would let the server handle all the physics I would end up with a very overwhelmed server with clients that only control one entity on the server.

Question:

What if i only use the server as a 'router' to control the traffic between clients and use one of the clients to handle the physics and do some checking to stop cheating?  Is this a bad idea? ( But this may increase latency, since clients can't send data directly to each other.)

Keep in mind that a game is between 2 players, that means the client which would handle the physics wouldn't have all clients body handled by it's pc.