texts:
I'm having an issue with the Pygame module. I run Python 3.2 and installed the respective Pygame file, but now when I try to import it in the IDLE, it gives me this error:

>>> import pygame
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pygame
  File "C:\Python32\lib\site-packages\pygame\__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application.

Any help will be appreciated.


texts: Unity animator causing lights to turn on sluggishly?

texts: I've got lights on a vehicle that I am controlling using several animations. I have an animator with multiple layers and everything works properly. However, I am having an issue where the lights take roughly half a second to reach full brightness. In the inspector, it does not show the intensity rising from 0-3, it just shows them already set to 3. If I preview the animation without the controller, the lights are on instantly. But for whatever reason, when running through the controller, they "come on slowly", not like when you flip a switch and lights are instantly "on", these turn on and take time to reach full brightness. I have ensured I do not have an exit time, and do not have fixed duration checked, and transition duration is set to 0. I have also tried to speed up the animation "Speed" property just to see if it would change anything but had no effect. Does any one have any idea why this is happening? thank you!


texts:
I been google searching on how to mod Game Maker games (Hyper-Light-Drifter to be more specific) but so far everyone says it's impossible to mod the files. The reason I want to do this is I want to learn to program by modding first and seeing examples that is already made, I also really like this game.

If there is a more better place/website to ask this question please tell me.


texts:
I am dealing with geometry shaders using GL_ARB_geometry_shader4 extension.

My code goes like :

GLfloat vertices[] =
    {
        0.5,0.25,1.0,
        0.5,0.75,1.0,
        -0.5,0.75,1.0,
        -0.5,0.25,1.0,
        0.6,0.35,1.0,
        0.6,0.85,1.0,
        -0.6,0.85,1.0,
        -0.6,0.35,1.0
    };

glProgramParameteriEXT(psId, GL_GEOMETRY_INPUT_TYPE_EXT, GL_TRIANGLES);

glProgramParameteriEXT(psId, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP);

glLinkProgram(psId);

glBindAttribLocation(psId,0,"Position");

glEnableVertexAttribArray (0);

glVertexAttribPointer(0, 3, GL_FLOAT, 0, 0, vertices);

glDrawArrays(GL_TRIANGLE_STRIP,0,4);

My vertex shader is :

#version 150

in vec3 Position;

void main()
{
    gl_Position = vec4(Position,1.0);

}

Geometry shader is :

#version 150
#extension GL_EXT_geometry_shader4 : enable

in vec4 pos[3];

void main()
{
   int i;
   vec4 vertex;

    gl_Position = pos[0];
    EmitVertex();

    gl_Position = pos[1];
    EmitVertex();

    gl_Position = pos[2];
    EmitVertex();

    gl_Position = pos[0] + vec4(0.3,0.0,0.0,0.0);
    EmitVertex();

    EndPrimitive();
}

Nothing is rendered with this code. What exactly should be the mode in glDrawArrays() ? How does the GL_GEOMETRY_OUTPUT_TYPE_EXT parameter will affect glDrawArrays() ?

What I expect is 3 vertices will be passed on to Geometry Shader and using those we construct a primitive of size 4 (assuming GL_TRIANGLE_STRIP requires 4 vertices). Can somebody please throw some light on this ?


texts: Typedef redefinition error when running Unity iOS project in Xcode 9 simulator

texts:
I was able to run my Unity 2017.1.0b10 iOS project successfully on my iPhone 6S+ (Using Xcode 9). I changed the Target SDK to Simulator SDK to try it out on other device simulators then I got the following errors in the UnityMetalSupport.h file.

Below are screenshots of my player settings:


texts: What do html5 game buyers/sponsors do with the game?

texts:
I understand there are html5 devs who make contracts with companies: they allow them to use their games for payment.

My question is how do these companies use these games to their benefit: what purposes do they have in forming these contracts and how does "buying" html5 games helps them accomplish it?

For example, if their purpose is generate money, how do they employ the html5 games for this goal?


texts: Directional, Triangular Collision Detection in Pygame

texts: I am trying to create a game in Pygame, with Python 3, and am trying to figure out an algorithm that will tell me which direction a rectangle is colliding with a rectangle, so that I can push it back the correct direction. I know I can detect rect-to-rect, and I could (possibly?) use pixel-to-pixel collision, but I was wondering if there was a better way. My collision algorithm currently loops through all of the "entity" objects in a Pygame sprite.Group(), and testing for collision using the colliderect() method, then I test which direction the rect is coming from by testing which sides overlap. Is there something similar that I could do with a collision between a triangle and a rectangle, too? Pseudocode would be nice.


texts: If I have a mesh of triangles and going to make a selection on it using a region (and not rectangle using   Glu.gluPickMatrix(...);), how can I implement it?


texts:
Well, I'm trying to code a gui for my engine, but I've got some problems.
I know how to make a UI overlay but buttons are still black magic for me. Anything I tried was to compilcated ( if it goes big ). To Example I tried to look if the mouse position is the same as the Pixel that is showing the button. But If I use some bigger areas it's getting to complicated. Now I'm searching for a Tutorial how to implement your own gui.
I'm really confused about it.
Well I hope you have/ know some good tutorials.

By the way, I took a look at the DXUTSample, but it's to big to get overview.


texts: unity3d - Fire bullet using AddForce is very slow

texts:
This is a top-down view but in 3D coordinates, I would like to instantiate and fire a bullet from the player's gun. This script is on a spawner object at the end of the barrel.

void Fire () {

        float speed = 80;

        GameObject projectile = Instantiate (bullet, transform.position, transform.rotation) as GameObject;

        projectile.GetComponent<Rigidbody>().AddForce(transform.forward * speed);
        coolDown += Time.time;
    }

I also tried this but in this case the bullet always moves in a fixed direction (North) :

projectile.GetComponent<Rigidbody>().velocity = Vector3.forward * speed;

Bullet is an empty object and the actual bullet is it's child ( did that to overcome a rotation issue ), the problem is nomatter how high I turn up the speed the bullet travels very very slow.
Both the parent and the bullet have Rigidbody.


texts:
I'm using cubemaps to render a skybox, in my game. Thinking this would be a simple task, I threw some stuff together using the tutorials I found online, particularly this one. Taking all of this together, I then adjusted the program to compensate for my particularly junky Linux laptop, by converting the GLSL to 120. However, this turned sour when I discovered that the texture I was loading, which is just a straight black line meant to test this very issue, is being horribly bent by my program. A short clip of my problem is shown on Youtube, here. In desperation, I asked this question on gamedev.net, without much success.

My Shader code looks like this:

Vertex Shader

#version 120
attribute vec3 verPos;

uniform mat4 MVP;
uniform vec3 camPos;
varying vec3 texCoord;
void main(){

    vec4 vertexPosition = vec4(verPos, 1.0);
    texCoord = verPos;
    gl_Position = MVP * vertexPosition;

}

Fragment Shader

#version 120

varying vec3 texCoord;
uniform samplerCube CubeMap;

void main()
{
    gl_FragColor = textureCube(CubeMap, texCoord);
}

Rendering Code

To avoid being spammy, I'll just assume that I loaded the images correctly, and not show off that particular mess. I'm using IMAGE_Load from SDL2 to handle the texture loading, and I made the cube map clamp to edge and such.

void SkyBox::Draw(){
    if(!loadedCheck) return;
    glUseProgram(myProgID);
    glDisable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glm::mat4 perspect = glm::perspective(45.0f, float(640) / float(480), 0.1f, 3000.0f);
    vector3f playerPos = player.myNPC.myEnt.myObject.getPosition();
    float playerAngY = player.myNPC.myEnt.myObject.myAngle.y;

    camPos = glm::vec3(-15.0f * float(cos(-playerAngY + 1.62)), 0,
        -15.0f *   float(sin(-playerAngY + 1.62)));

    //Convert my vector3f class to glm::vec3
    glm::vec3 playerGLM = glm::vec3(playerPos.x, playerPos.y, playerPos.z);
    float playerAngX = player.myNPC.myEnt.myObject.myAngle.x;

    //camPos is the position of the camera relative to the player's position
    glm::mat4 view = glm::lookAt(camPos + playerGLM, playerGLM, glm::vec3(0,1,0));
   // view = glm::mat4(glm::mat3(view));
   //To get rid of the translation matrix
    view[3][0] = 0;
    view[3][1] = 0;
    view[3][2] = 0;
    //comb is equivalent to an MVP matrix
    glm::mat4 comb = perspect * view;

    GLuint matrixID = glGetUniformLocation(myProgID, "MVP");
    glUniformMatrix4fv(matrixID, 1, GL_FALSE, glm::value_ptr(comb));

    GLuint camID = glGetUniformLocation(myProgID, "camPos");
    GLuint sampler = glGetUniformLocation(myProgID, "CubeMap");
    float camP[3] = {camPos.x, camPos.y, camPos.z};
    glUniform3fv(camID, 3, camP);

    glActiveTexture(GL_TEXTURE0 + 0);

    glBindTexture(GL_TEXTURE_CUBE_MAP, myTexture);

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glEnableVertexAttribArray(verAttrib);
    glVertexAttribPointer(
        verAttrib,
        3,
        GL_FLOAT,
        GL_FALSE,
        0,
        (void*)0
    );

    glDrawArrays(GL_TRIANGLES, 0, 36);

    glDepthFunc(GL_LESS);
    glEnable(GL_DEPTH_TEST);

}

All in all, I feel like this should be working. Why am I experiencing weird texture warping?


texts:
What protocol is used to develop real time update games over the internet? From my research here is what I understood:

You cant make one device (phone) as server to host room, you need real server not sure why.
UDP have better performance but the data packet may get lost on the way
TCP HTTP is the easiest way (what I am familiar with) my question here should I use REST and call the server each second from the clients(phones) to update game status or is there a way where the server can update the client?


texts:
I'm making a clone of an old atari 2600 game, so it's simple, only slightly more complex than the original.

I'm realizing that even the simplest of games have different "parts", what is a good design method to be able to test those sections without having to "play through" to that part?

Specifically, (it's a "breakout" clone) if I'm modifying and testing code that runs when the game is beaten, I don't want to have to play through the whole game just to see if my code works. I can only imagine how complicated this kind of testing is for a game of substantial size.

How do real devs make their game such that they can test just a certain section, or test a section under certain possible in-game circumstances without having to play through to that part?


texts: How do I play a particle system when moving?

texts:
I have a car that I move with a Physics-based movement (AddForce(), AddTorque(), etc...) and I have a simple particle system attached behind the car as follows:

I'd like to play this ParticleSystem whenever the car moves; I tried checking if the car's rigidbody's velocity was greater than 0:

if(m_Rigidbody.velocity.z > 0)
   m_ParticleSystem.Play();

if(m_Rigidbody.velocity.z == 0 && m_ParticleSystem.isPlaying) // velocity.z == 0 is unreliable, verified with Debug.Log
   m_ParticleSystem.Stop();

I then tried using Input:

if(Input.GetAxis("Vertical") > 0) // the car is moving along the positive z axis
    m_ParticleSystem.Play();
if(Input.GetAxis("Vertical") == 0 && m_ParticleSystem.isPlaying)
    m_ParticleSystem.Stop();

These two methods don't work, I'm probably making assumptions on how Rigidbody.velocity behaves (when you stop the car for example, it becomes negative, so the particle system would keep playing until it reaches 0);


texts: Sprite animation with "overlapping" animations?

texts:
I'm trying to implement my own sprite animation system, and so far I've got it working quite nicely. I store each animation as a "take" which basically denotes the row of the animation in the sprite sheet, the starting frame and the number of frame. These takes are created during start-up and played by calling play(takeID) on the animation. The player is split into four sprites: head, torso, arms and legs, and different animations can be played on each of these separately from the other parts.

Now, this works fine for situations where I only need a single animation (walking, idling, running, swinging a sword etc.), but I need a more complex animation system for situations where the player performs multiple things at the same time, for example walking while swinging a sword.

I've tried to break down the requirements of the animation system by using the example above, and I've found these cases:

1. Player swings the sword
    1.1. Play swinging animation
    1.2. When done, play idle animation

2. Player starts walking
    2.1. Play walking animation until player stops
    2.2. Play idle animation when player stops

3. Player walks and swings the sword
    3.1. Play walking animation
    3.2. Replace the animation of the hands by a swinging animation
    3.3. When swinging animation is done, revert back to the "walking hands" animation

4. Player walks, initiates a swing and stops walking during the swing
    4.1. Play walking animation
    4.2. Replace the animation of the hands by a swinging animation
    4.3. (Player stops walking during the swing)
    4.4. Stop walking animation and play idle animation for
         all other body parts except the hands
    4.5. When swinging animation is done, play idle animation for hands

I've tried fiddling around with "overriding" animations where the animation with the higher priority (in this case, the "swinging" animation) would be shown instead of the lower priority animation (the walking animation) while updating still both simultaneously to maintain the correct rhythm of the original animation. However, I have trouble getting it to work properly.

The "reversion to idle animation" is a rather challenging task: if I have just the single walking animation, I can stop it and then play the idle animation (or rather, the "idle frame"), but when the sword swinging is added, it becomes more difficult to know when to swap to the idle animation.

So, to conclude with my question: has anyone faced a similar problem? How should I tackle this issue?


texts: Deployed Android APK file size was more tha expected when developed in Unity

texts:
I developed a game, and build it as an Android APK file. I was not using any assets, only a UI panel and a UI Button. I thought the APK file woul be 3 MB, but it was 18MB.

On the Google Play store, there are many good games using good graphics that have a small size. Some are only 5MB or 6MB. I want to know why I am getting such a large APK file.

How do I reduce the size of my APK file?


texts: How do I pass arguments to an XNA Game executable?

texts:
How do for example make it possible to pass an argument to the .exe file and read it in my XNA Game?

Examples:

Enable Editor:

game.exe -devmode

Set Resolution:

game.exe -width 1280 -height 720

and in the game check the arguments before starting the game.  I searched for this earlier and thought about it again but found nothing about it.


texts: Making a cube follow my finger in Unity2d?

texts: I would like to make a cube follow my finger when i touch an iphone screen and drag in unity 2d.


texts: Why does Unity allow me to use GameObjects created from non-existent prefabs?

texts:
I have code similar to the following in a Unity project. I was trying to shoot a
projectile when spacebar was hit, but a projectile wasn't appearing. I found out the problem was caused because I moved my bullet prefab to /Assets/Resources/prefabs/bullet.prefab. Bullets started appearing upon updating the string in Resources.Load, but I then questioned why I didn't encounter some sort of runtime error when I tried to perform operations on the non-existent bullet.

if (Input.GetKeyDown(KeyCode.space))
{
    // Bullet is actually in /Assets/Resources/prefabs/bullet, so this won't find it.
    var bullet = Resources.Load("bullet") as GameObject;
    bullet.transform.position = new Vector3(0, 0, 0);
    Instantiate(bullet);
}

Could someone please tell me why Unity doesn't throw an exception or any sort of runtime error when loading a resource that doesn't exist? Maybe there are exceptions/recoveries happening but I just didn't notice because the game updates much faster than I can push the space bar?


texts: Is character movement with an animated sprite controlled by the animation itself or moved manually?

texts:
How is a walking animation of a given character designed? I can see two possible ways:

The first way is to draw each frame of the animation such that, if the frames are displayed at position (0,0), the character walk but does not really move (I mean: at frame 10, the character is still at the left, upper corner of the screen). This means that one needs a way to move (translate) the frames manually.

The other way is to draw each frame such that their width grows progressively. Drawing the frame i at position (0,0) will give the impression that the character is really moving (not only walking on the same point). This way is the graphic artist that do all the job, but the animation is completely controlled by him, so he can give a specific style to the walking animation.

The first one seems to be the right way to do things, but one would need a way to say: ok, frame 0 last 50 ms at (0,0), frame 1 last 30 ms at (5, 0), frame 2 last 15 ms at (13, 0) etc...

This makes things much more complicated.

What is the best practices? What way do you usually adopt/suggest?


texts: If there is an Alpha version, and a Beta version, are the full releases called Gamma or something?

texts:
Given the first release of a game is named "Alpha", and another is named "Beta", it would be logical that the release following this one is named "Gamma".

This this the case?


texts:
I am using cellular automata to randomly generate caves in Unity. Attached is a screenshot:

The black area represents walls. Walls can contain resources that can be mined.

Walls are made of blocks. A block should be destroyed when it is mined.

The naive approach would be to render a cube for each wall block. This won't work though because it will require too many objects to be on screen at once, even if the wall blocks are clipped to the viewport.

So how should I go about this? I was considering grouping sections of wall blocks together in a single mesh. When a block is destroyed, the mesh would be re-rendered with vertices for the block removed.

Or is there a better way?


texts:
I'm trying to allow the user to pan a 2D scene by using the touch screen.  I have tried several methods including translating the projection matrix, translating the view matrix and haven't found anything that will work.  With these methods, the screen either pans extremely fast, or doesn't pan the amount that the user has moved with their finger.
The closest I've got is the following:

public void onDrawFrame(GL10 glUnused) {
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

    // Projection matrix setup
    Matrix.frustumM(projectionMatrix, 0, -mSurfaceRatio * zoomFactor, // Left
        mSurfaceRatio * zoomFactor, // Right
        -1 * zoomFactor, // Bottom
        zoomFactor, // Top
        3, // Near
        7); // Far

    // panning
    Matrix.translateM(projectionMatrix, 0, mPositionX, mPositionY, 0);

    for (IDrawable drawable : mDrawables) {
        drawable.Draw(maPositionHandle, maTextureHandle, mvpMatrixHandle, mvpMatrix, viewMatrix, projectionMatrix);
    }
}

Gesture Detector:

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
    float distanceY) {

    boolean panned = false;

    float currentZoomFactor = renderer.getZoomFactor();

    if (distanceX != 0) {
        renderer.mPositionX += -1f * (distanceX * (3.1f /renderer.mSurfaceWidth) * currentZoomFactor * renderer.mSurfaceRatio);
        panned = true;
    }

    if (distanceY != 0) {
        renderer.mPositionY += (distanceY * (3.8f /renderer.mSurfaceHeight) * currentZoomFactor * renderer.mSurfaceRatio);
        panned = true;
    }

    if (panned)
    {
        surfaceView.requestRender();
    }

    return panned;
}

Code for calculating the surface:

public void onSurfaceChanged(GL10 glUnused, int width, int height)
{
    GLES20.glViewport(0, 0, width, height);
    mSurfaceRatio = (float)width / height;
    mSurfaceWidth = (float)width;
    mSurfaceHeight = (float)height;
}

This code will pan somewhat correctly, but I just guessed at the 3.1f and 3.8f to make it look right.  By somewhat I mean that when the device (Xoom tablet) is held long-wise the area pans correctly in the x direction, but in the y direction, the scene will lag behind where the user's finger is moving.

Could someone help me with this?  Thanks!


texts: Local avoidance together with any-angle types of A* Pathfinding

texts:
Recently I have been implementing the Block A* any-angle path-finding algorithm in a project I have, for which I need extremely efficient results due to the large number of NPCs. However, I still do not know exactly how to handle the problem of local avoidance between the NPCs moving at the same time in the same scene.

So, my question is this: what is the best method to implement local avoidance with any-angle path-finding? Just testing for LOS and steering to the tangent of the predicted encounter is a good enough solution or should a specific AI implementation be included within the pathfinding routine?

I would highly appreciate references (academical or not) with state-of-the-art implementations of local avoidance for me to explore the most recent developments in that field.

Many thanks.


texts:
I've been trying to get a swept collision detection up and running now for almost a week and I can't for the life of me get it working.

There is a answer on this linked here below:
Swept AABB vs Line Segment 2D
I've translated this into Go which will be running the game server and needs this logic:
func SweepRectLine(rectX, rectY, rectW, rectH, rectHSpeed, rectVSpeed, lineX1, lineY1, lineX2, lineY2 float64) (bool, float64) {
    outVel := [2]float64{}
    // hitNormal := [2]float64{}
    lineNX, lineNY := lineX2-lineX1, lineY2-lineY1
    // lineMinX, lineMaxX, lineMinY, lineMaxY := math.Min(lineX1, lineX2), math.Max(lineX1, lineX2), math.Min(lineY1, lineY2), math.Max(lineY1, lineY2)
    var lineMinX, lineMaxX, lineMinY, lineMaxY float64
    if lineNX > 0 {
        lineMinX, lineMaxX = lineX1, lineX2
    } else {
        lineMinX, lineMaxX = lineX2, lineX1
    }
    if lineNY > 0 {
        lineMinY, lineMaxY = lineY1, lineY2
    } else {
        lineMinY, lineMaxY = lineY2, lineY1
    }
    r := (rectW/2)*math.Abs(lineNX) + (rectH/2)*math.Abs(lineNY) //radius to Line
    boxProj := (lineX1-rectX)*lineNX + (lineY1-rectY)*lineNY
    velProj := rectHSpeed*lineNX + rectVSpeed*lineNY

    if velProj < 0 {
        r *= -1
    }

    hitTime := math.Max((boxProj-r)/velProj, 0)
    outTime := math.Min((boxProj+r)/velProj, 1)
    // log.Println("start", hitTime, outTime)

    rectXMax, rectXMin := rectX+rectW/2, rectX-rectW/2
    if rectHSpeed < 0 { // left
        if rectXMax < lineMinX {
            return false, 0
        }
        hitTime = math.Max((lineMaxX-rectXMin)/rectHSpeed, hitTime)
        outTime = math.Min((lineMinX-rectXMax)/rectHSpeed, outTime)
    } else if rectHSpeed > 0 { // right
        if rectXMin > lineMaxX {
            return false, 0
        }
        hitTime = math.Max((lineMinX-rectXMax)/rectHSpeed, hitTime)
        outTime = math.Min((lineMaxX-rectXMin)/rectHSpeed, outTime)
        // log.Println("right", hitTime, outTime)
    } else {
        if lineMinX > rectXMax || lineMaxX < rectXMin {
            return false, 0
        }
    }

    if hitTime > outTime {
        return false, 0
    }

    rectYMax, rectYMin := rectY+rectH/2, rectY-rectH/2
    if rectVSpeed < 0 { // up
        if rectYMax < lineMinY {
            return false, 0
        }
        hitTime = math.Max((lineMaxY-rectYMin)/rectVSpeed, hitTime)
        outTime = math.Min((lineMinY-rectYMax)/rectVSpeed, outTime)
    } else if rectVSpeed > 0 { // down
        if rectYMin > lineMaxY {
            return false, 0
        }
        hitTime = math.Max((lineMinY-rectYMax)/rectVSpeed, hitTime)
        outTime = math.Min((lineMaxY-rectYMin)/rectVSpeed, outTime)
    } else {
        if lineMinY > rectYMax || lineMaxY < rectYMin {
            return false, 0
        }
    }

    if hitTime > outTime {
        return false, 0
    }

    outVel[0] = rectHSpeed * hitTime
    outVel[1] = rectVSpeed * hitTime
    return true, hitTime
}

I also put up a Gist with a executable UI here: https://gist.github.com/KidLinus/3f847c46b0e6dc1addac7252d9cb54ab
I can't for the life of me figure out what all class variables stand for. I think that some of them are native to Unity but that's just a guess. I've come so far as to figure out that the extent is half of the width/height in said direction. What the "line.n" stands for is anyones guess, I assume its the direction and have no idea if it's normalized or not.
There are also a couple of dead variables just laying there.


texts:
Possible Duplicate:
  Detect Open Space in Farseer
  How do I detect ledges?

I'm making a 2D platformer with Box2D. The player needs to be able to grab onto a ledge and pull him/herself up.

Right now I have a sensor that extends in every direction from the upper half of the player's body.

The logic seems simple enough: if there are tiles inside the sensor and empty space above them, then it's a ledge and the game should act accordingly. The problem is that I can't figure out how to implement that logic with Box2D.

Anyone have any ideas?


texts: Need Help With My Script And Animator. I am encountering a few bugs with it

texts:
Okay so I have created a player archer character which when he using the arrow keys, faces those directions and upon hitting space when in that direction, the bow attack animation is played.

The code works fine but there are some nerve-wrecking problems:

when I unpress an arrow key, the character always returns to his default direction and when I press space when no arrow key is pressed, the right bow attack animation is played and also when i press the up arrow key and the space bar, the up bow attack animation does not play and instead again,the right bow attack animation is played.

I have looked at everything again and again but I can't seem to find anything wrong. The animation's assigned are okay and the code is okay too. Don't know what's wrong. I have been stuck at this problem all day.

I have attached some screenshots so you can see how I have achieved this:

my animator here

my blend tree in the idle state is here
and so far, this is my script:

public class PlayerDirectionAndShooting : MonoBehaviour
{
     Rigidbody2D rbody;
     Animator anim;

     void Start ()
     {
         rbody = GetComponent<Rigidbody2D>();
         anim = GetComponent<Animator>();
     }

     void Update ()
     {
         Vector2 direction_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
         anim.SetFloat("input_x", direction_vector.x);
         anim.SetFloat("input_y", direction_vector.y);

         if (Input.GetKeyDown("space"))
         {
            if (anim.GetFloat("input_x") <= -1)
            {
                anim.SetBool("is_shooting_left", true);
            }
         }
        else
        {
            anim.SetBool("is_shooting_left", false);
        }

        if (Input.GetKeyDown("space"))
        {
            if (anim.GetFloat("input_y") <= -1)
            {
                anim.SetBool("is_shooting_down", true);
            }
        }
        else
        {
          anim.SetBool("is_shooting_down", false);
        }

        if (Input.GetKeyDown("space"))
        {
            if (anim.GetFloat("input_y") <= 1)
            {
               anim.SetBool("is_shooting_up", true);
            }
        }
        else
        {
            anim.SetBool("is_shooting_up", false);
        }

        if (Input.GetKeyDown("space"))
        {
            if (anim.GetFloat("input_x") <= 1)
            {
                anim.SetBool("is_shooting_right", true);
            }
        }
        else
        {
            anim.SetBool("is_shooting_right",false);
        }
    }
}


texts: C# - How to properly play background songs in XNA

texts:
So I'm using the game states (enum) to change my game screens. I have 2 songs for main menu and game playing states, respectively. To play songs, I'm using an old code example I saw at MSDN, like this:

bool songStart = false;
Song song1;
Song song2;

// LoadContent method:
song1 = Content.Load<Song>(".\\Songs\\mainMenuTheme");
song2 = Content.Load<Song>(".\\Songs\\mainGameTheme");
MediaPlayer.IsRepeating = true;

// Update method:
switch (CurrentGameState)
{
case gameState.mainMenu:
        if (CurrentGameState == gameState.mainMenu && !songStart)
    {
        MediaPlayer.Stop();
        MediaPlayer.Play(song);
        songStart = true;
    }
    else if (CurrentGameState != gameState.mainMenu && songStart == true)
    {
        MediaPlayer.Stop();
        songStart = false;
    }
break;
case gameState.gamePlaying:
        if (CurrentGameState == gameState.gamePlaying && !m_SongStart)
        {
            MediaPlayer.Stop();
            MediaPlayer.Play(song2);
            m_SongStart = true;
        }
        else if (CurrentGameState != gameState.gamePlaying && songStart == true)
        {
            MediaPlayer.Stop();
            songStart = false;
        }
break;

So if I am in mainMenu, the first song plays; when I go to gamePalying the first song stops and the second one starts playing. If I return to mainMenu, the mainMenu song plays. My issue however, is that if I click Play game and the state moves to gamePlaying there is no background music! What could've caused the problem? Please help me fix it, I'm stuck for a whole week.


texts:
I followed some advices to learn Slick2D and when I started doing the "SimpleGame" I got my first error. Does anyone have any idea of what is it and how to fix?

Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:Slick Build #274
Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:LWJGL Version: 2.0b1
Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:OriginalDisplayMode: 1024 x 768 x 16 @60Hz
Sun Dec 26 23:09:12 GMT-03:00 2010 INFO:TargetDisplayMode: 800 x 600 x 0 @0Hz
Sun Dec 26 23:09:12 GMT-03:00 2010 ERROR:Could not find a valid pixel format
org.lwjgl.LWJGLException: Could not find a valid pixel format
 at org.lwjgl.opengl.WindowsPeerInfo.nChoosePixelFormat(Native Method)
 at org.lwjgl.opengl.WindowsPeerInfo.choosePixelFormat(WindowsPeerInfo.java:52)
 at org.lwjgl.opengl.WindowsDisplayPeerInfo.initDC(WindowsDisplayPeerInfo.java:54)
 at org.lwjgl.opengl.WindowsDisplay.createWindow(WindowsDisplay.java:158)
 at org.lwjgl.opengl.Display.createWindow(Display.java:299)
 at org.lwjgl.opengl.Display.create(Display.java:848)
 at org.lwjgl.opengl.Display.create(Display.java:800)
 at org.newdawn.slick.AppGameContainer.tryCreateDisplay(AppGameContainer.java:299)
 at org.newdawn.slick.AppGameContainer.access$000(AppGameContainer.java:34)
 at org.newdawn.slick.AppGameContainer$2.run(AppGameContainer.java:364)
 at java.security.AccessController.doPrivileged(Native Method)
 at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:345)
 at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
 at SimpleGame.main(SimpleGame.java:38)
Exception in thread "main" org.newdawn.slick.SlickException: Failed to initialise the LWJGL display
 at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:375)
 at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
 at SimpleGame.main(SimpleGame.java:38)


texts: Detect left and right movement of sprite

texts:
I have a sprite of ball which moves when a player tap and holds the ball and move finger on the screen. I have a attached animations on it. straight, left, right and when the ball hits something.

Here is my code:
ball.cs

 public RuntimeAnimatorController straight;
    public RuntimeAnimatorController left;
    public RuntimeAnimatorController right;
    public RuntimeAnimatorController ballHit;

    Animator animator;
    Vector2 prevPos;

    private void Start()
    {
        animator = gameObject.GetComponent<Animator>();
    }

    void Update ()
     {

         //Gets the world position of the mouse on the screen
         Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

         //Checks whether the mouse is over the sprite
         bool overSprite = this.GetComponent<SpriteRenderer>().bounds.Contains(mousePosition);
         if(GameObject.Find("GameController").GetComponent<brickMovement>().gameOver == true)
        {

            animator.applyRootMotion = true;
            animator.updateMode = AnimatorUpdateMode.UnscaledTime;
            animator.runtimeAnimatorController = ballHit;
        }
         //If it's over the sprite
         if (overSprite)
         {
             //If we've pressed down on the mouse (or touched on the iphone)
             if (Input.GetButton("Fire1") && GameObject.Find("GameController").GetComponent<brickMovement>().gamepaused == false && GameObject.Find("GameController").GetComponent<brickMovement>().gameOver == false)
             {
                 float x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
                 float y = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
                 //Set the position to the mouse position
                 prevPos = this.transform.position;

                 //Debug.Log(animator.runtimeAnimatorController);
                 if ((x > -1.938 && y > -4.51) && (x < 1.98 && y < 4.5))
                 {
                    //Debug.Log("Previous Pos: " + prevPos.x);
                    Debug.Log(IsThisObjectMoving());
                    if (this.transform.position.x < 0 && IsThisObjectMoving())
                     {
                        animator.runtimeAnimatorController = left;
                     }
                     else if (this.transform.position.x > 0 && IsThisObjectMoving())
                     {
                        animator.runtimeAnimatorController = right;
                     }
                     else if (this.transform.position.x == prevPos.x)
                     {
                        animator.runtimeAnimatorController = straight;
                     }
                     this.transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                     Camera.main.ScreenToWorldPoint(Input.mousePosition).y,
                     0.0f);
                 }
             }
         }
     }

    bool IsThisObjectMoving()
    {
        Vector3 sek0pos;
        Vector3 sek1pos;

        sek0pos = gameObject.transform.position;
        StartCoroutine(delay());
        sek1pos = gameObject.transform.position;

        if ((sek1pos.x - sek0pos.x) > 0f)
            return true;
        else
            return false;
    }

    /*

    Make function out of the above function that will check if object is
    moving left or right.

    */
    IEnumerator delay()
    {
        yield return new WaitForSeconds(1.0f);
    }

I am having issue in detecting if ball is moving left or right. When ball is not moving straight animation should be played. but when it is the respective direction animation should be played.

Secondly when I do a hit animation it ends quickly without getting played properly.


texts: How can I insert random numbers in specific place in text of UI Text?

texts:
I have a Canvas with Text and a Panel.
I want that it will show random numbers between 3 and 10 between the almost and hours:

  Hello my friend, It's about time to wakeup. You were sleeping for almost...hours. My name is NAVI and i'm your navigation helper in the game.

Sometimes when running the game I was sleeping for almost 5 hours and sometimes when running the game I was sleeping for almost 3 hours.

For example:

  Hello my friend, It's about time to wakeup. You were sleeping for almost 5 hours. My name is NAVI and i'm your navigation helper in the game.

Instead the 3 dots to add a random number.


texts: Formula Racing Physics in curves (under-steer, over-steer)

texts:
I have a working physics code for a -let's say-  WipeOut-style vehicle [well, closest approximation]. Some time next year I would like to do a formula game but am struggling to get to tweak my code to behave anywhere near the way the formula (say, like in F1 GP game that ran on 100 MHz Pentiums) behaves in curves.
Visually, think 3D engine and a 3D track (with hills/valleys - but still a track (not a generic heightmap)).
Since the target HW is below 100 MHz and code is written in ASM, we can't use any off-the-shelf physics engines, but it must be written from scratch (initial prototyping will be done in C++ for max productivity and understanding of limitations of the physics component).
Now, I don't have any issue with the following (already working):

non-linear acceleration (e.g. each gear range has different constants/behavior)
hill-based acceleration/decceleration (how steep hill is)
car gets lighter over time (less gas in the tank), affecting acceleration
each parameter can have an additional modifier (linear, non-linear) applied to it over the time

My greatest issue is I can't seem to get the thing to over-steer / under-steer in curves.
I want to allow the player to choose several different levels of physics - from Arcade, through gradually more realistic features, to a full-blown (as far as manageable by me) physics (like in F1GP game). So far, I have these racing physics modes implemented:

Arcade racing (kinda like in Lotus/Outrun)
gear-specific non-linear acceleration (each formula has different characteristics)
hill-based speed-up/down (steepness)
speed-based drag in curves (how quickly car reacts to turning)
tire temperature gradually rising (affecting all physics ranges, modifiers and constants)

Through trial&error I found a way how to get the car to turn faster/slower based on current speed. It works pretty well, but it won't realistically skid the car away from the track (like F1GP does).
Also, nowhere in the code, I actually use any vectors. It's all just constants, valid ranges, and type of applied modifier (none/speed-up/down, linear/non-linear) that we use on the desired variable, as that's the fastest possible way on given platform (all these values fit into available CPU's registers, unlike vectors that have to be read from slow RAM).
So, how does one actually get the car to under-steer/over-steer in curves ? What's the actual physics here ? Rigid Body ? I believe it should be perfectly possible to emulate this feature via 2D vectors (car direction + speed) ?


texts:
I have a game that I'm developing in Unity.
The game will be released for Android, so I'm working with the Google Play Console.
The thing here is that I don't know how to block (Made not available) some devices with certain properties.
For example, I need to made my game NOT available for tablets and for devices that don't have at least 1 GB of RAM.
Does anyone know how can I do this?


texts: How to control which polygons get rendered first in a batch (e.g. to draw leaves)?

texts:
Sorting transparent objects is a well-known problem. If you send a bunch of transparent polygons (e. g. leaves and branches on a tree) into the GPU and render them with alpha blending enabled, the GPU will sort the polygons randomly.

But what I noticed is that although they get sorted randomly, the order of rendering is always the same. If it wasn't the leaves would flicker as their colors change, depending on which layer they are on.

How can I control which polygons get rendered when? Maybe their order depends on the index buffer?

[EDIT] To clarify things: I know that different Draw() calls execute precisely in the order they were issued. I am trying to figure out how to manipulate the polygon order inside a single Draw() call. If a tree has a hundred polygons it is a waste do draw evey single one separately and a pain in the artists'... behind. So what I need is to influence the order of rendering for a bunch of polygons in a single pair vertex and index buffers.

Yes and I am working with XNA 4.0.


texts: Debugging a custom content pipeline processor in XNA?

texts:
I'm working with a custom made content pipeline designed to work with the program Tiled (using the TiledLibrary found here). I am running into trouble with the MapProcessor class in the custom content pipeline, and would like to be able to debug it to find out what exactly is going on.

However, when I try to use lines such as Console.WriteLine(...) or breakpoints, these lines are ignored by the debugger built into Visual Studio. Is the content pipeline barred from access to things like console writing and breakpoints? If so, is there a way to fix this?

I'm a bit new to C#, XNA, and Visual Studio, so bear with me if this is a dumb question. I tried googling my problem (as well as searching this stackexchange) but was unable to find any answers. Thanks!


texts:
Ok, I've got a weird one here.  I'm trying to make a basic tile engine using a windows form, but some of my code is just...not happening.  I'll post the chunks in question.

private void MapEditor_Load(object sender, EventArgs e)
    {
        LoadImageList();
        FixScrollBarScales();
        cboCodeValues.Items.Clear();
        cboCodeValues.Items.Add("ENEMY");
        cboCodeValues.Items.Add("CHEST");
        cboCodeValues.Items.Add("NPC");

        for (int x = 0; x < 100; x++)
            cboMapNumber.Items.Add(x.ToString().PadLeft(3, '0'));

        cboMapNumber.SelectedIndex = 0;
        TileMap.EditorMode = true;
        backgroundToolStripMenuItem.Checked = true;
    }

This should be called when the form loads, right?  The code dives into LoadImageList(), which contains:

private void LoadImageList()
    {
        string filepath = Application.StartupPath + @"\Content\Textures\IndoorTileSet.png";
        Bitmap tileSheet = new Bitmap(filepath);
        int tilecount = 0;
        for(int y = 0; y < tileSheet.Height / TileMap.TileHeight; y++)
        {
            for(int x = 0; x < tileSheet.Width / TileMap.TileWidth; x++)
            {
                Bitmap newBitmap = tileSheet.Clone(new System.Drawing.Rectangle(x * TileMap.TileWidth, y * TileMap.TileHeight,
                    TileMap.TileWidth, TileMap.TileHeight), System.Drawing.Imaging.PixelFormat.DontCare);
                imgListTiles.Images.Add(newBitmap);
                string itemName = "";
                if(tilecount == 0)
                    itemName = "Empty";
                if(tilecount == 1)
                    itemName = "Floor";
                listTiles.Items.Add(new ListViewItem(itemName, tilecount++));
            }
        }
    }

The bitmap loads correctly, but then the entire MapEditor_Load method just stops working.  tileCount seems to be a local variable in the debugger, and its value is 0, but the debugger never executes the breakpoint on the line which it is assigned.  I have absolutely no idea why it would do this, and it's driving me nuts.  Any help?
Oh, I put the bitmap load in a try/catch block just to see if it was handling an exception in a weird way, but I had no luck.  It's not throwing an exception.  I began having this problem immediately after replacing my IndoorTileSet with an updated version.


texts:
I'm making some visualization of the Earth. It just should display tiles from services like Google Map (OpenMap for example) on the Earth surface. This services provide Earth satellite image textures of different parts of Earth at different zoom levels (resolution). The goal is make something similar with Google Earth.

Of course I want to load only visible tiles at appropriate zoom level depending on distance to the camera center. So I'm interesting in how to decide which tiles on which levels should I load depending on current camera position.

I know how to find region on the Earth surface that currently visible depending on camera view and projection matrix. And I can calculate the desired resolution (zoom level) of tiles for each point inside this region. Now, how to find out tile coordinates and zooms that I need to download form OpenMap or similar services? Is there some algorithm to do it?


texts: OpenGL - Multiple Render Target - write only to some targets, discard others

texts:
In OpenGL, is it possible to achieve behaviour like this:

out float out1
out vec4 out2;

//.....

out1 = /* write some value */
out2 = /* discard */

My output targets are R32F and RGBA.


texts: Unity: Shader Outlined/Uniform uses undefined Queue: 'Geometry + 1'

texts:
my outline shader was working fine but suddenly it started throwing this error. the game still works fine in the editor though but when i try to build it gets stuck on the step:

Packing assets - sharedassets0.assets

this is my shader:

Shader "Outlined/Uniform"
{
    Properties
    {
        _Color("Main Color", Color) = (0.5,0.5,0.5,1)
        _MainTex ("Texture", 2D) = "white" {}
        _OutlineColor ("Outline color", Color) = (0,0,0,1)
        _OutlineWidth ("Outlines width", Range (0.0, 2.0)) = 1.1
    }

    CGINCLUDE
    #include "UnityCG.cginc"

    struct appdata
    {
        float4 vertex : POSITION;
    };

    struct v2f
    {
        float4 pos : POSITION;
    };

    uniform float _OutlineWidth;
    uniform float4 _OutlineColor;
    uniform sampler2D _MainTex;
    uniform float4 _Color;

    ENDCG

    SubShader
    {
        Tags{ "Queue" = "Geometry + 1" "IgnoreProjector" = "True" }

        Pass //Outline
        {
            ZWrite Off
            Cull Front
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag

            v2f vert(appdata v)
            {
                appdata original = v;
                v.vertex.xyz += _OutlineWidth * normalize(v.vertex.xyz);

                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                return o;

            }

            half4 frag(v2f i) : COLOR
            {
                return _OutlineColor;
            }

            ENDCG
        }

        Tags{ "Queue" = "Geometry"}

        CGPROGRAM
        #pragma surface surf Lambert

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    Fallback "Diffuse"
}

i tried looking on the internet but couldn't get any help on this error.


texts: I've created a planet and obstacle grid and want to move units through this grid using A* or any other algorithm. The only problem is wrapping. I need a simple example of how to handle this unusual pathfinding requirement. I prefer C#/XNA rather than C++.


texts: How to linearly "blend" between multiple 3D points?

texts:
I have a set of 3D points that I need to "blend" between. Lets say I have points [A,B,C] and I have the amount I want to blend each as [0.5, 0.2, 0.8], how can I blend between these points with the amount I need?
Obviously if I just had 2 points I could use the vector math (A + (B - A) * ratio).
Method 1:
I'm currently using a weighted average, which I suppose gives me the weighted center, but I need to try different blending styles to see visually which looks best.
Method 2 What If I did this:

Calculated a difference vector, each 3D point against the default point (I do have a default point)
A - Default

Then multiplied this difference with the blend amount
(A - Default) * Amount

And added these up, would that work? What result would I get?
(A - Default) * A_Amount + (B - Default) * B_Amount + (C - Default) * C_Amount


texts:
I have been working on a level-of-detail program. Right now I have the rough structure down (splitting of quads without condensing of quads). But the problem is that when you try to split certain quads after they are 1/8 the size of the original they sometimes do not split and the quads that should have been placed in that spot are in another place. I think I just need someone else to look at this code, I believe the problem rests in the index of the quads...
Here is the main code:

public Quad(Vector3f v1, Vector3f v2, Vector3f v3, Vector3f v4,float size,int x, int y,boolean has,float pI, float pI2){
    first = v1;
    second = v2;
    third = v3;
    fourth = v4;
    width = size;
    index1 = x;
    index2 = y;
    children = has;
    parentIn1 = pI;
    parentIn2 = pI2;

}
public static ArrayList<Vector3f> makeVerts(Vector3f p, int x, int y, float increment){
    ArrayList<Vector3f> list = new ArrayList<Vector3f>();
    Vector3f back_left = new Vector3f ((float)x*increment, 0 , (float)y*increment).add(p);
    Vector3f front_right = new Vector3f ((float)(x*increment) + increment, 0, (float)(y*increment)+increment).add(p);
    Vector3f front_left = new Vector3f ((float)x*increment, 0 , (float)(y*increment)+increment).add(p);
    Vector3f back_right = new Vector3f((float)(x*increment) + increment, 0, (float)y*increment).add(p);

    list.add(back_left);
    list.add(front_left);
    list.add(front_right);
    list.add(back_right);
    return list;
}

public static void create(Quad quad, int i, int ii){
    quad.children = true;
    i+=quad.parentIn1;
    ii+=quad.parentIn2;
    System.out.println(i+ " "+ii);
    Vector3f parent = new Vector3f(i*quad.width, 0, ii*quad.width);
    //System.out.println(parent + " "+ toString(quad));
    if(quads == null){
        quads = new Quad[2][2];
        for(int x = 0; x<2; x++){
            for(int y = 0; y<2; y++){
                float growth = quad.width/2;
                ArrayList<Vector3f> points = makeVerts(parent,x,y,growth);
                Vector3f p1 = points.get(0);
                Vector3f p2 = points.get(1);
                Vector3f p3 = points.get(2);
                Vector3f p4 = points.get(3);
                quads[x][y] = new Quad(p1,p2,p3,p4,growth, (int) (x+quad.index1),(int)(y+quad.index2),false,quad.index1,quad.index2);
                list.add(quads[x][y]);
        }

    }
}

    }

In addition here is the code that creates the first quad and divides it into four:

Vector3f v1 = new Vector3f(0,0,0);
Vector3f v2 = new Vector3f(0,0,32);
Vector3f v3 = new Vector3f(32,0,32);
Vector3f v4 = new Vector3f(32,0,0);
Quad q = new Quad(v1,v2,v3,v4,32,0,0,false,0,0);
Quad.create(q,0,0);
v.addAll(Quad.getPoints());
Quad.reset();

And the code that divides quads depending on one's distance:

   for(int i = 0; i<Quad.list.size(); i++){
        Quad q = Quad.list.get(i);
        Vector3f center = Quad.getCenter(q);
        float width = q.width;
        float distance = center.distance(cam.getLocation());
    if(width/distance >= .85 && !q.children){
        Quad.reset();
        Quad.create(q,q.index1,q.index2);
        VertexBuffer vb = mesh.getBuffer(Type.Position);
        v.clear();
        v.addAll(Quad.getPoints());
        verts = new Vector3f[v.size()];
        v.toArray(verts);
        vb.updateData(BufferUtils.createFloatBuffer(verts));

parentIn1&2 are the indices of the parent quad. Index1&2 are the indices of the quad. Each time a quad needs to divided the "create" method is run...
Just for an idea of what is happening here is a shot of the actual scene. On this run I zoomed in exactly on the center of the quad and this was the result..

Thanks for any and all help, it is much appreciated.


texts: What is an efficient way to manage uniforms in a game?

texts:
Most engines on the market have their drawbacks and it's difficult to find a simple/light-weight one that's open-source and doesn't have to put you through a rather complex learning process. Writing one is a difficult task on its own, but it might not be a bad idea if what you want that engine to do is to support a specific kind of games (e.g. 2.5 D games on mobile devices).

So, in search for a good game engine architecture, I've found a few logistical issues. Consider this scenario:

Objects:

Each object is comprised of two principle structures of render information:

a model (geometry mainly) and
a material (that tells the object what textures and what shaders to use).

Of course, it is natural to allow an object to switch its material definition on the fly. But a material encapsulates the shaders, so these drag along with them some slots for uniforms and vertex attributes.

Since an uniform, for example, can be:

object specific (color, specular exponent, etc.)
global/superglobal (lights, weather conditions/fog/wind,etc.) or
specific to a group of objects (they all have, let's say, a reflectivity factor)

then it means that it's wrong to put them in either the object's property region or in the material's property region. It's clear that both uniforms and attributes are always declared in the shader sections of a material, but where their values come from is an enigma in the frames of a pretty general rendering engine. You have to allow for the existence of numerous types (by semnatics!) of uniforms: position, colour, bone matrices, indices, lighting parameters, etc.

The big question now: how would you suggest to organize and manage uniforms? (especially the information flow - they're declared by shaders, but their values are supplied by apparently different type of entities - some renderable, some more abstract, being themselves controllers or managers).


texts:
I'm creating the code, where a player swinging on a rope

for the moment I got this

double angle = Math.atan2(player_y - center_y, player_x - center_x) - Math.atan2(end_y - center_y, end_x - center_x);
if (direction == 'right') {
    player_x += 10;
    player_y += 10 * angle;
} else {
    player_x -= 10;
    player_y -= 10 * angle;
}

I know that I have to add gravity, speed, etc... but I'm not very good in physics. The question is How do I make rope swinging more realistic?

I don't use any engines or frameworks, only native canvas.

EDIT

Tried this code.

onStart...
angle0 = Math.atan2(player_y - center_y, player_x - center_x) - Math.atan2(end_y - center_y, end_x - center_x);
length = Math.hypot(center_x - player_x, center_y - player_y);
swing_start = System.currentTimeMillis();
T = 2 * Math.PI * Math.sqrt(length / 9.8f);

onDraw...
elapsed_time = (System.currentTimeMillis() - swing_start) / 1000;

#with this player makes a very slow circle with the wrong pivot point
player_x += Math.sin((2 * Math.PI / T) * elapsed_time);
player_y += Math.cos((2 * Math.PI / T) * elapsed_time);

#with this it makes backwards circle
double angle = angle0 * Math.cos((2 * Math.PI / T) * elapsed_time);
player_x += Math.sin(angle)
player_y += Math.cos(angle);

Where am I wrong?

onDraw called every 25ms

Log...
start - 15:31:22.411

﹕ T: 39.83959786319781 angle: 1.1898202456306484
+15 the same
﹕ T: 39.83959786319781 angle: 1.175053634797472
+18
﹕ T: 39.83959786319781 angle: 1.13112033295045
+18
﹕ T: 39.83959786319781 angle: 1.059110834176187
+17
﹕ T: 39.83959786319781 angle: 0.9608125282061935
+17
﹕ T: 39.83959786319781 angle: 0.9608125282061935
+17
﹕ T: 39.83959786319781 angle: 0.6957011399544965
+17

end - 15:31:29.361


texts:
I'm currently working with a mesh class so I can easily create mesh objects. Now I want a draw function in my mesh class so when ever i want draw it to the screen I can just call it without any fuss. But i have run in to a dilema and i need some insperation/ other persons perspectiv. To draw a mesh object there is alot of thing you need. You need blend states, rasterizer state, depth stencils ect (lets call them "tools" for futher reference).

Now there is a couple of diffrent ways you can go about it and i wanted your input to choose one.

You can have the object create their own tools. It requires more space, but you dont have to pass pointer around as much.
You create the tools in the GameEngine object and pass pointers to the tools in the draw function parameters. It looks messy and could cost alot of time, but it take up less space.
You create the tools in the GameEngine object and then store pointers to them in the mesh object. Now this save both time and space, however i got the feeling that this could get really messy and caus you alot of trouble easily.

I greatly appriceate any feedback or diffrent solutions. Thank in advance.


texts: Collision detection optimization for a top down shooter

texts:
I'm relatively new to game development and have been trying to learn how collision detection is coded. I mostly work with Actionscript 3, but I'm learning C++ on the side.

I've been wondering how "bullet hell" and top-down shooters optimize their collision detection with so many objects.

Any information/theories would be great.


texts: How do I find the shape of Tiled's circles or ellipses in libGDX?

texts:
I created a level in the 'Tiled Map Editor' and loaded it into my libGDX game.
I can easily transform almost all objects into Box2D objects (although this problem is not Box2D specific), but I have trouble with ellipses.

Tiled seems to only create ellipse objects, without a special case for circles. I'd be happy with just circles if they existed in Tiled.

However, even the EllipseMapObject I load in libGDX only has an x,y position. I don't see any information about area or vertices. Did I miss something? How can I create circle or ellipse objects in Tiled and load them into libGDX with right dimensions?

Tiled version 0.10.1, libGDX version 1.4.1


texts: How do I know what to do with incoming network messages?

texts:
I am programming a 2D game in a server/client architecture with C# and lidgren. When a client sends a message to the server, how does the server know what to do with that message data?

The client could send different kinds of things, for example the coordinates of player 1 and 2 or the health. So how does the server know its the coordinates and stuff?


texts: Swift Spritekit: Create realistic driving sprite

texts:
How would I go by creating a realistic driving experience?

I'm using iOS Swift 3 with SpriteKit using the functions applyForce to accelerate when I click the gas button and when braking I add friction to the physicsBody, also I can't seem to turn right, no idea on how to do it.

Right now for turning I'm splitting the screen using the left and right to turn but I'm using applyForce but its very bad because it turns when the car is stopped and in a very unrealistic way.

When I apply force its only to go up so if I do create a turning mechanism and I do a uturn the car will still go up.

Also side note: Multitouch doesn't work?

Any help? Thanks

override func didMove(to view: SKView) {

    // Multi Touch
    self.view?.isMultipleTouchEnabled = true

    car.carNode.position = CGPoint(x: 0, y: 0)
    car.carNode.physicsBody = SKPhysicsBody(rectangleOf: car.carNode.size)
    car.carNode.physicsBody?.affectedByGravity = false
    car.carNode.physicsBody?.angularDamping = 0.1
    car.carNode.physicsBody?.linearDamping = 0.1
    car.carNode.physicsBody?.friction = 0.1
    car.carNode.physicsBody?.mass = 1

    self.addChild(car.carNode)

    // HUD Display
    gas.gasButton.position = CGPoint(x: 300, y: -500)
    self.addChild(gas.gasButton)

    brake.brakeButton.position = CGPoint(x: 150, y: -500)
    self.addChild(brake.brakeButton)

}

override func update(_ currentTime: TimeInterval) {

if touching {

    car.carNode.physicsBody?.applyForce(CGVector(dx: 0, dy: 180))
  }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

for touch in touches {
    let location = touch.location(in: self)

    if location.x < self.frame.size.width / 2 {

        // Left side of the screen
        car.carNode.physicsBody?.applyForce(CGVector(dx: -100, dy: 0))

    } else {

        // Right side of the screen
        car.carNode.physicsBody?.applyForce(CGVector(dx: 100, dy: 0))
    }

    // Gas Button
    if (gas.gasButton.contains(location)) {

        touching = true
    }
        // Brake Button
    else if (brake.brakeButton.contains(location)) {

        car.carNode.physicsBody?.friction = 1
    }

  }
}


texts:
Sorry for the bad title, but I couldn't think of a way to word my problem for a title.

So I have this script, with two classes:

using UnityEngine;
using System.Collections;

public class GameItem {

    public string ItemName { get; set; }

    public string ItemDesc { get; set; }

    public Item_Type ItemType { get; set; }

    public int ItemValue { get; set; }

    public int ItemID { get; set; }

    public GameItem() {

    }

    public GameItem(string name, string desc, Item_Type type, int value, int id) {
        this.ItemName = name;
        this.ItemDesc = desc;
        this.ItemType = type;
        this.ItemValue = value;
        this.ItemID = id;
    }
}

public class Weapon : GameItem {

    public string WeapEnch { get; set; }

    public float WeapEffic { get; set; }

    public Weapon() {

    }

    public Weapon(string name, string desc, string ench, float effic, int id) {
        this.ItemType = Item_Type.WEAPON;
        this.ItemName = name;
        this.ItemDesc = desc;
        this.WeapEnch = ench;
        this.WeapEffic = effic;
        this.ItemID = id;
    }

    public void Attack() {

    }
}

public enum Item_Type {
    APPAREL,
    WEAPON,
    TOOL,
    CONSUMABLE,
    BOOK,
    MISC
}

And then I have a script for adding items to a list using the constructors:

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

public class InventoryManager : MonoBehaviour {

    public List<GameItem> GameItems { get; set; }

    void Start () {
        GameItems.Add(new Weapon("Sword", "It's just a sword.", null, 5, 0));
    }

    void Update () {
        if(Input.GetButtonDown("Interact")) {
            Debug.Log(GameItems[0].ItemName);
        }
    }
}

So when I create a new Weapon in the list, I can access everything from the GameItem class, but nothing from the Weapon class, even though I used the Weapon constructor. So I can't use the Attack () function, or access the Weapon's variables. How can I get around this problem?


texts: How can I support multiple player inputs in Pygame?

texts:
I'm trying to develop a team-based Asteroids game. It's going well except for the "multiple user inputs to a single machine" part. Can anyone recommend a method for getting and updating 6 players using a single computer? Is it even possible? At the moment I'm working with a couple of old XBox controllers and a keyboard and it's almost working...

Is it possible to add additional keyboards? And would you arrange the code into one big get events function or is there a better way to check for user inputs at this scale?


texts:
I am currently programming a multiplayer game. The basic idea is that the game uses Command Pattern for any actions that happens in the game. If the player right clicks to move then a command is issued to the selected object to move to the location.
I implemented gRPC to include multiplayer. Here is my problem, when the player right clicks on the ground I send a gRPC call with that command then the server acknowledges the commands and sends it back to all the clients, the client then processes the command and everything goes well. Now if the player enters the game while a command is underway the client never received that command so its never process on the client.
What would be a good way to fix this problem without sending the info of all the actors (x,y,z) and what they are doing at each server ticks?
Thanks!


texts: Model View Controller linking dynamic model to view

texts:
I currently an implementing a game roughly using a model-view-controller setup. A single game controller instantiates a model and view. The model and view then instantiate child models and views, respectively passing references to the need models and view between them.

That works fine if the models and view are known at runtime (e.g. things that are guaranteed to exist such as the main character). My problem is when the model spawns game object models at certain times during gameplay (e.g, a randomly generated pickup). There needs to be a way for a view to also be created and the model passed as a reference to it. Of course, the model shouldn't have access to the view, but the view does have access to the model. What's a clean way to implement a system so that views can be dynamically generated and linked to their model counterparts?

One idea I had was the model can contain an array of "new" models that have not had views assigned to them already. When the view updates, it creates new views for each element in the array, assigns the models to themselves, and removes the element from the array. Thoughts? Thanks ahead of time.


texts: Hard edges with non power of 2 images in OpenGL

texts:
When down scaling 2D images in Java2D, it does a great job at preserving hard edges while downscaling to non power of 2s. However, in OpenGL, I have been unable to find a solution to this. I have tried using GL_NEAREST to get hard edges, but it also creates the wonky edges aswell. I cannot use GL_LINEAR in this case either, but still, the linear interpolation still looks wonky.

Example (Both rendering 30x30 hard image, rendering at 30x30 pixels).

Please note : I am aware that this occurs with images that aren't power of twos, like 30, but the main problem is, if I try to upscale or downscale an image that is power of two (say 16x16) to something that isn't a power of two (say 20x20), I still get this effect. This issue with scaling this occurs in Java2D, but it is by far less noticable.

My question is: What parameters will I need to use when rendering a non power of two image? So I can get a similar effect that I get in Java 2D.

I can post source code if needed.

EDIT

Original Image (30 x 30 png)

Turns out I wasn't scaling them at all! Both were being rendered at the original 30 x 30 pixels on both OpenGL and Java2D.

Sample Code:
Java2D:

 g.drawImage(heart, 0, 0, 30, 30, null);

No rendering hints are being applied, just the bare minimum.

In OpenGL

Vertex Shader:

#version 400

in vec2 position;

out vec2 textureCoords;

uniform float width;
uniform float height;
uniform float xOffset;
uniform float yOffset;
uniform mat4 transformationMatrix;

void main(void)
{

    gl_Position = transformationMatrix * vec4(position.x, position.y, 0.0, 1.0);
    gl_Position.x += (xOffset) / (width / 2);
    gl_Position.y += (yOffset) / (height / 2);
    gl_Position.y = gl_Position.y;

    textureCoords = vec2(position.x / 1, position.y / 1);
}

Fragment Shader:

#version 400

in vec2 textureCoords;

out vec4 out_Color;

uniform sampler2D texture2d;
uniform float transparency;

void main()
{
    out_Color = texture2D(texture2d, vec2(textureCoords.x, textureCoords.y));
    if(textureCoords.y > 1 || textureCoords.y < 0)
    {
        discard;
    }
}

Rendering methods:

public void makeWonkyImage()
{
    render(0, 0, 30, 30, heart);
}
public void render(float x, float y, float width, float height, int textureID)
{
    PostProcess.imageRenderer.render(x, Gfx.HEIGHT - y, width / 1000, -height / 1000, textureID);
}
public void render(float x, float y, float width, float height, int textureID)
{
        shader.start();

        prepare(textureID);
        Vector2f position = new Vector2f((-Display.WIDTH / (width * 1000f))
                , (-Display.HEIGHT / (height * 1000f)));
        Matrix4f matrix = Maths.createTransformationMatrix(position,
                new Vector2f(width / Gfx.WIDTH * 1000f, height / Gfx.HEIGHT * 1000f));
        shader.loadTransformation(matrix);
        shader.loadScreenDimensions((float) Display.getWidth(), (float) Display.getHeight());
        shader.loadOffsets(x, y);
        GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, quad.getVertexCount());
        end();
        shader.stop();
}

public void prepare(int texture)
{
        GL30.glBindVertexArray(quad.getVaoID());
        GL20.glEnableVertexAttribArray(0);
        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

        GL11.glDisable(GL11.GL_DEPTH_TEST);
        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture);
        GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
}


texts: The best option to multi-platform 2d mobile development

texts: we are in the process of porting a game from iphone(made with cocos2s) to android(using the andEngine), and it has been a pain to do. So for our next project (a 2d game) we are thinking about using some multiplatform engine/framework. For now we are thinking about testing both unity, marmaled(former airplay sdk) and cocos2d-x. Do you have any opinion about this? Does someon have experience developing 2d games using Unity?


texts: Unity C# Microphone input in Android different than on PC?

texts:
I'm working on a mobile app inside Unity, in which I need to input and repeat microphone input almost immediately..

I've worked it out and it works great when I play it from within the Unity Editor. I get some very strange behavior though when I try it from my Android phone (Galaxy Note 3)..

So I decided to run some tests and noticed quite different behavior..

Using this sample code:

using UnityEngine;
using System.Collections;

public class testingMicScript : MonoBehaviour {

    void Start () {
        audio.loop = true;
        audio.clip = Microphone.Start (null,true,10,44100);
        while(!(Microphone.GetPosition(null)>0)){}
        audio.Play ();
    }
}

and playing it from withing the Editor it works great, I speak and hear myself back after a few milliseconds. I compile the app and run it from my phone and when I speak I get a very strange echo which goes on until the sound is completely distorted and I get a strange hiss, until audio is completely muted..

Why is that? Is there any particular setting I should go through? Or do I have to change something in my code?


texts: Tailoring sound volume for different speakers

texts:
Different sound effects are played differently across different speakers. For example, when I use my laptop speakers, sounds are notably softer and low pitch sounds often become inaudible unless I turn my volume up from 20% to 80%. Yet if I try to increase the sound's amplitude, when I plug in my Creative T10 speakers, everything sounds too loud.

My problem is that I cannot increase sound uniformly across the board just to make the soft sounds more audible on a laptop, since as mentioned, everything sounds perfectly balanced on good speakers, it's just bad speakers (laptops) that ruin things.

What options do I have to ensure the volume is consistent across different speaker configurations?

PS: I'm using Flash, so there's no way to check hardware.


texts: Box2d pathfinding using raytracing / predicted collisions

texts:
I have a Box2d/Cocos2d iOS game with enemies that attempt to follow the player (to attack). I'm working on improving the pathfinding logic so that the enemies won't crash into objects in the world.

Using raytracing, I know when there's an obstacle between an enemy and the player. I know when the enemy can't see the player.

I'm attempting to find a good way for the enemy to navigate around the obstacle, no matter what direction it's facing.

Right now, I start with the angle between the enemy and the obstacle. I gradually increment the angle, looking for any on-obstructed path that will allow the enemy to travel further than the obstacle's distance. This seems to work well so far, but it doesn't take into account the size of the enemy.

For example, if I have a 32px-squared enemy, the raytrace may find a clear path that would involve the edges of the ship hitting an obstacle.

Is there a way I can run a raytrace, predict collisions for something with a known width? Or is there a better way for my enemies to navigate around an obstacle.


texts:
I am trying to figure out how XNA is actually projecting a 3d world space coordinate to screen space.

I decompiled the MonoGame framework and copied the CreateLookAt und CreatePerspectiveFieldOfView methods of Matrix and multiplied thereafter  3 vectors like XNA does:

First multiply each position with world, then multiply resultig new vector4 with view and then the new resulting vector4 finally by projection.

      public static Vector2<T> Project(Vector3<T> source, Matrix4x4<T> world, Matrix4x4<T> view, Matrix4x4<T> projection, int width, int height)
    {
        Vector4<T> worldPosition = world * new Vector4<T>(source.X.ParseToNumeric<T>(), source.Y.ParseToNumeric<T>(), source.Z.ParseToNumeric<T>(), 1);
        Vector4<T> viewPosition = view * worldPosition;
        Vector4<T> position = projection * viewPosition;

        var X = position.X.ParseToNumeric<T>();
        var Y = position.Y.ParseToNumeric<T>();
        var Z = position.Z.ParseToNumeric<T>();

        return new Vector2<T>((X / Z) + width / 2, (Y / Z) + height / 2);

    }

Because (0,0,0) would be the center of the screen I added to the corresponding X and Y coordinates width and height divided by 2. Just because it made sense I divided finally the xy components by z.

The result is sobering:

I used following matrices:

      basicEffect.World = Matrix.Identity;
        basicEffect.View = Matrix.CreateLookAt(new Vector3(0, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0));
        basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000.0f);

And these points:

            vertices[0] = new VertexPositionColor(new Vector3(0, 0, 2), Color.Red);
        vertices[1] = new VertexPositionColor(new Vector3(1, 0, 2), Color.Red);
        vertices[2] = new VertexPositionColor(new Vector3(0, 1, 2), Color.Red);

Do you know why this happens?


texts: What is the simplest way to calculate distance in a 3D environment?

texts:
What is the simplest way to programmatically calculate difference between two points in a 3D game environment?

I am trying to sort a list of light sources by how close they are to an entity, so that only the four closest light sources affect an entity at any given time.


texts:
I have the following script on my object:

public class PlayMyCube : MonoBehaviour
{
    [SerializeField] private Animator myAnimationController;

    private void onTriggerEnter(Collider other) {
        if (other.CompareTag("Player")) {
            myAnimationController.SetBool("playSpin2", true);
        }
    }

    private void OnTriggerExit(Collider other) {
        if (other.CompareTag("Player")) {
            myAnimationController.SetBool("playSpin2", false);
        }
    }
}

When the player character is inside the first cube's trigger, my second cube should play a spinning animation. When they leave, the second cube should stop.

But what happens in the game now is, when the character runs into the trigger, it does nothing.

I have configured my trigger object like this:

I have configured the object that should spin like this:

And configured the Animation Controller like this:

And configured my Player object like this:

What can I do to make this animation play when the player is inside the trigger?


texts: I'm working on a glow shader (for 2D engine Futile relying on Unity). It works OK but the effect is limited by the texture area. Except from adding a lot of empty pixels around the textures (which would result in un-optimized/too big texture atlases), is there a better solution to cope with this problem? I'm quite new with shaders so maybe this is a classic problem with some well known solutions, maybe I'm not searching with the right keywords.


texts:
I am attempting to understand the easeljs ColorFilter and its use with cache.  There is quite a bit of information at the easeljs site but it's not clear based upon the examples and documentation.

Draws the display object into a new canvas, which is then used for subsequent draws.

cache (x, y, width, height, [scale=1])

For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25:

var shape = new createjs.Shape();
shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 25);
myShape.cache(-25, -25, 50, 50);

Using that example I loaded an image/bitmap ("ball") and am trying to apply a transformation to change the color.

ball.filters = [
    new createjs.ColorFilter(0,0,0,1, r(255),r(255),r(255),0)
];

ball.cache(-50, -50, ballImage.width, ballImage.height);

You can see from the before and after images below the results I've generated.

The documentation states that the new cache object is written into another canvas "off screen" but the transformation appears to only be applied where the cache overlaps the image.  The image below represents my understanding of this.

Can someone clarify how the ColorFilter and cache are to be used?  Ultimately I'm only trying to apply a color change to a bitmap.


texts:
I had been developing a Maze Game which is dragging a bitmap down on the maze going on the finish line. on first my game response quickly on my onTouch and dragging and after couples of
adding toast message, generate random mazes, changing character from drawCircle into a bitmap and a background from a solid color into a customize PNG file my game seems to Slows Down.

Can anyone explain why could this happen?

And what should I do to make my game to response more quickly?

Tnx for the help and godbless.

UPDATE: I found out that it all started when i change my solid color background to a bitmap background.

here's my code:

From this:

protected void onDraw(Canvas canvas)
canvas.drawRect(0, 0, width, height, background);

To this:

protected void onDraw(Canvas canvas) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.menu_bg);
//Set Rectangle Size and Coordinates
RectF rect = new RectF(0,0,width,height);
//Maze with Background
canvas.drawBitmap(bitmap, null, rect, null);


texts: Proper way to supply different textures and multiply matrices for thousand of terrain meshes

texts:
What I have

Terrain chunks of size 64x64 meters in a custom format
PVR textures
OpenGLES2 renderer
GLSL shader

None of the above can be changed in any way, i.e. I can't modify the existing code of shader or change the renderer.

Terrain

Each terrain chunk consists of 64 tiles of size 8x8 meters and are placed in a grid. Each tile has 3 layers of textures so theoretically there can be 192 different textures per chunk.

The way I currently load terrain is via script. I create a mesh for every tile in a chunk, so that's 64 meshes per chunk.

Shader

The shader input consist of:

3 textures and their texture mask
3 matrices
minor stuff

The matrices needed are calculated in every frame in the following way:

var M = _object.transform.localToWorldMatrix;
var V = Camera.main.worldToCameraMatrix;
var P = Camera.main.projectionMatrix;
_material.SetMatrix("WorldViewProjectionMatrix", P * V * M);
_material.SetMatrix("WorldViewT", (V * M).transpose);
_material.SetMatrix("World", M);

What I need

Loading the entire terrain would take a lot of time and resources, so I only load the nearest chunks depending on player position and its a 5x5 chunks area. And still on average I have:

25 chunks
25 * 64 = 1600 tile meshes
25 * 64 = 1600 materials
up to 25 * 192 = 4800 different textures (only theoretically! Currently there is no more than 20-30 per chunk and the average across loaded chunk is about 300 textures)
about 6400 matrix operations

The amount of materials does not seem to have a huge impact on performance, but the matrix calculates make the fps drop from ~80FPS to ~12. I could've reduced the matrix operations down to 100 if I could render single chunk as a single mesh instead of 64 submeshes, but I don't see a way to properly pass the textures to shader.

So basically what I need is an approach that would allow me to render terrain chunk as a single mesh and a way to pass different textures for different tile parts of a mesh. Do I even look in the right direction?


texts: How to Check and Destroy "linked" gems quickly efficiently

texts:
Engine: Gamemaker Studio

(simplified) Situation: I have a 6x6 board (at this moment) stored in a 2D matrix, a mechanism for linking adjacent squares, similar to Puzzlecraft, and a button that confirms the link - adding the resources, and destroying the instances of the squares, then moving existing squares and generating new ones.

Question: Is there a way to instantly go through the linked squares, and not just check for any instances marked as linked = true.

Efficiency is in all likelihood not a true concern, especially on this tiny scale, but I'd like to know for the sake of self-improvement more than anything.

Idea for Solving it: I've thought of a way that may be fairly lightweight and quick, I don't know if it is though:

Once a square is added to the link, put the square's position in the matrix in a separate array (one which has 36 slots, in case the entire board is linked). Then once the button to confirm is pressed, it goes up from the bottom of the array, until it reaches a null or -1 value - destroying and setting the value of this array at the appropriate position to null or -1.

Question on the idea: Would this work? How would I store the square's position in the matrix in this array? Would I need to make the array 2D so that it can hold both the x and y position of the square [ie. 0 to 5]?


texts: Sphere to plane collision never rearching resting contact

texts:
I have been trying to have a sphere to plane eventually lead to the sphere coming to a resting contact, but my sphere will end up always bouncing forever. It will bounce correctly for the first few times, but eventually it will just be in a constant state of a very small bounce. I have tried to exhaust every article I can find but I don't see where I am going wrong here. Does anyone see the issue? I have attempted to put as much information into this post so I apologize if it is a bit long.

I first attempt to see if there is resting contact, collision, no collision or if the sphere and plane will collide

Vector3 forces = (sphereTotalForces + sphereVelocity);
float denom = Vec3Dot(&plane->GetNormal(), &forces);

if(sphereVelocity.GetMagnitude() > 0 && dist <= sphereRadius + .0013f) {
    crCollisionResult.enCollisionState = RESTING_CONTACT;
    crCollisionResult.vCollisionNormal = plane->GetNormal();
    return crCollisionResult;
}
else if(fabs(dist) + 0.001f <= sphere->GetRadius()) {
    crCollisionResult.enCollisionState = COLLISION_HAS;
    return crCollisionResult;
}
else if(denom * dist > 0.0f) {
    crCollisionResult.enCollisionState = COLLISION_NO;
    return crCollisionResult;
}

where

sphereRadius  = 1
denom = -9.98206139
dist = 2.34482479

Since none of those are true I will then attempt to calculate when the collision will happen

    F32 fIntersectionTime = (sphere->GetRadius() - dist) / denom;
    F32 r;
    if(dist > 0.0f)
        r = sphere->GetRadius();
    else
        r = -sphere->GetRadius();

    Vector3 collision = spherePosition + fIntersectionTime * rigidBodySphere->GetVelocity() - r * plane->GetNormal();
    crCollisionResult.fCollisionTime = fIntersectionTime;
    crCollisionResult.vCollisionNormal = plane->GetNormal();
    crCollisionResult.vAdjustedPosition = collision;

The intersection time will be calculated to be 0.00334050134 , which is less than the fElapsedTime of 0.00703109941. As a result, I will update my sphere using the intersection time as the delta (so fElapsedTime here will be 0.00334050134)

    mAcceleration = mTotalForces / mMass;
    mVelocity += mAcceleration * fElapsedTime;
    Vector3 translation = (mVelocity * fElapsedTime);

    mTransform->Translate(translation.x, translation.y, translation.z);

    mTotalForces = Vector3(0.0f, 0.0f, 0.0f);

where

mTotalForces = (0, -10, 0)
mMass = 22

After I update there sphere with its new position, I will then calculate the new velocity of it being reflected

        Vector3 vSurfaceNormalized;
        Vec3Normalize(&vSurfaceNormalized, &crCollisionResult.vCollisionNormal);

        Vector3 vIncomingVelocity = pSphere->GetVelocity();
        F32 fIDotN = Vec3Dot(&vIncomingVelocity, &vSurfaceNormalized);

        Vector3 vReflectedVelocity = vIncomingVelocity - ((1.0f+pSphere->GetCoefficientOfRestitution()) * vSurfaceNormalized * fIDotN);
        pSphere->SetVelocity(vReflectedVelocity);

where

pSphere->mCoefficientOfRestitution = .85
vIncomingVelocity = (0, -5.30, 0)
mNormal = (0, 1, 0)
fIDotN = -5.30350208
vReflectedVelocity = (0, 4.50797653)


texts: How do I make a turn based game for two players who play with different devices on iOS?

texts:
I only have experience in physics-based games in cocos2d.

I want to develop a turn-based game in Cocoa Touch (iOS). Two players will play this game on different devices which connect via Bluetooth or Game Center.

I'd like to know how to synchronise two devices through a Bluetooth connection.

Please tell me of any blog tutorial, guide, or sample code which will help.


texts: Loading Wavefront Data into VAO and Render It

texts:
I have successfully loaded a triangulated Wavefront (.obj) into 6 vectors, the first 3 vectors contain the locations for vertices, UV coords, and normals. The last three have the indices stored for each of the faces.

I have been looking into using VAO's and VBO's to render, and I'm not quite sure how to load and render the data. One of my biggest concerns is the fact that indexed rendering only allows you to have one array of indices, meaning I somehow have to make all of the first three vectors the same size, the only way I thought of doing this, is to make 3 new vertex's of equal size, and load in the data for each face, but that would completely defeat the purpose of indexing.

Any help would be appreciated.


texts: Texture mapping artifacts at triangle edge (for thin triangles?)

texts:
I'm working on generating programmatic textures for 3d models and showing them in WebGL using Threejs. To do this I generate a texture image (PNG) that contains per-triangle textures (a rectangle on the image, that is a rasterization of the 3d triangle), and an associated uv map. To prevent bleeding I generate a 2 pixel border around each triangle's texture rectangle in the resulting PNG. The rest of the texture image is black.
This results in visible artifact lines when rendering:

The texture sampler is set to use NearestFilter for magnification and minification, and the texture's wrapping is ClampToEdge for both S and T, which makes things even more confusing. I've also tried with bigger per-triangle image borders and the problem still persists.

This is the texture I generate:

These lines seem to overlap with thin triangles, which are rasterized to 2 pixels along the shortest axis.

I'm sure there is no physical gap in the model, because it renders fine as a solid, so it must be a texture sampling related thing, which is also confirmed by the fact that the color of the lines is affected by color of the "empty" parts of the texture. If I change those, then the line colors also change. I've also tried offsetting UVs by 0.5 / tex_size and the same thing is rendered.

Any help would be useful.

Thanks!


texts:
i'm trying to develop a simple multiplayer turn base game, i'm start creating the grid map, i have already write the javascript script to display the range movement for the specific unit, but my problem is how to check if the grid position sent to server by the client is a valid position, i think this is a operation to do on server side (i use php) because javascript is easy editable by the user, my first throught is to save in a database each tile and its data (example: is a water tile, a forest tile...), so when the position is send to server i can read the db and check if the position is valid, but i think this method is very slow and require a lot of server resources, so there is a better way to do this?
(i don't know if this is the correct site or is a question for StackOverflow)


texts: SAT - How to find Shortest line between two static convex 2D Polygons?

texts:
RI have a pretty standard SAT algorithm that seems to successfully be detecting collisions but now I am looking for some assistance in finding the shortest line between 2 separated Polygons.

I have spent quite a bit of time searching and trying things with no success.
If someone could point me in the correct direction or give a solution to this I would be most greatful.

While a general n polygon vs n polygon solution would be awesome my use case only requires OBB vs OBB. This could simplify the answer.


texts: Unity error after adding skybox material

texts:
So I added the night material from the fantasy skybox asset I download from the asset store and the rest of my objects turned white for some reason I figured it was just a glitch like the light baking and it would be okay when I deployed my project

Well I saved and built my project as usual and the objects all turn pink as if their materials did not exist and every time I go to play the game I receive the following error

'Assets/Build/ParcoreBeast_Data/Managed/Assembly-CSharp.dll' shouldn't be queried by IsAssemblyCompatible, missing IsInternalOrCompiledAssembly check ?
UnityEditorInternal.InternalEditorUtility:GetMonoIslands()
UnityEditor.SyncVS:SyncVisualStudioProjectIfItAlreadyExists()

How do I fix this?


texts:
textStyle = new LabelStyle();
textStyle.font = font;
textStyle.fontColor=Color.GREEN;

EnterTextCasheir= new Label("",textStyle);
EnterTextCasheir.setBounds(AssetsHelper.convertWidth(158),
        AssetsHelper.convertHeight(162),
        AssetsHelper.convertWidth(180),
        AssetsHelper.convertHeight(55));
EnterTextCasheir.setWrap(true);
EnterTextCasheir.setFontScale(1f, 1.5f);
EnterTextCasheir.setSize(CashierCounterEnterBoxZoomImage.getWidth(),
        CashierCounterEnterBoxZoomImage.getHeight());

table4.addActor(EnterTextCasheir);

EnterTextCasheir.addListener(new InputListener() {
    private boolean EnterTextCasheirBol;

    public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
        if(!EnterTextCasheirBol)
        {
            EnterTextCasheirBol = true;
            Gdx.input.getTextInput(new TextInputListener() {
                private String CasheirBoxStg;

                @Override
                public void input (String text) {
                    EnterTextCasheirBol = false;
                    EnterTextCasheir.setText(text);

                    CasheirBoxStg = (String) text;
                }
            }
        ...
        }
    }
}

Its my brief code;I am not able to display the text into single line ;its coming in 2 lines can anyone help me to resolve.Thank you


texts:
I have some problems with a rotating marble.
I've tried it with Matrix.CreateFromYawPitchRoll and Matrix.CreateRotation but there were some problems, I think it's due to the Gimbal lock effect.

So, I've tried using quaternions instead, but nothing changed.
When moving on only an axis it works fine, but when the rotation occurs on two different axes the marble still rotates on wrong axes.

Here's my code:

// declarations
Vector3 Position = Vector3.Zero;
Vector3 Rotation = Vector3.Zero;
Quaternion qRotation = Quaternion.Identity;

AbsoluteBoneTransforms = new Matrix[Model.Bones.Count];
            Model.CopyAbsoluteBoneTransformsTo(AbsoluteBoneTransforms);

In the Update method:

Position += speed;
Rotation = speed * MathHelper.ToRadians(-1.5f);

Quaternion rot = Quaternion.CreateFromAxisAngle(Vector3.Right, Rotation.Z) *
                Quaternion.CreateFromAxisAngle(Vector3.Backward, Rotation.X);

qRotation *= rot;

And in the Draw method:

effect.World = AbsoluteBoneTransforms[mesh.ParentBone.Index] *
  Matrix.CreateFromQuaternion(qRotation) * Matrix.CreateTranslation(Position);

What's wrong?

EDIT

I've tried calculating directly the axis of rotation of my marble, instead of using combination of multiple axes:

angle += speed.Length() * angularVelocity;
qRotation = Quaternion.CreateFromAxisAngle(Vector3.Cross(speed, Vector3.Up), angle);
qRotation.Normalize();

angle is a float that keeps track of the current movement.
This solution doesn't seem to create Gimbal lock, but marble rotations aren't correct, it seems that the rotating speed is not constant, but became faster and slower over time, I can't understand why.


texts: Is any Update() called always first than any LateUpdate() from other scripts?

texts: If a script is called at a specific moment in the script execution order, will every LateUpdate() functions from the rest of the objects work after that Update()? The documentation isn´t clear about it.


texts: Translate position from 3D camera to 2D camera

texts:
Currently I have 2 cameras, one for viewing the 3D objects (Perspective), and the other camera to view 2D objects (Orthographic).
(Also, the view of the camera never intercepts each other.)

I am trying to display a 2D object based on the position of a 3D object, like so:

What I have is the respective 2D and 3D Camera, as well as the Vector3 position of the 3D GameObject.

What I have tried:

public Vector2 Convert3DPositionTo2DPosition(Camera camera3D, Vector3 position3D, Camera camera2D) {
    var tempPos = camera3D.WorldToViewportPoint(position3D);

    return camera2D.ViewportToWorldPoint(tempPos);
}

The only problem is that the returned position is not completely aligned with the 3D position.
Which results in this kind of results:

Also, I have made sure that both the 3D and 2D object have their pivot point are set correctly in the center, but it still does not work as intended.

(I am currently using Unity 2019.1.14f1)


texts: What is the connection between an isometric angle and scale

texts:
I am trying to work out an isometric projection matrix for a custom angle.
In the engine I'm using there's a projection matrix defined like so:

projection.rotate(45 * (Math.PI / 180) );
scale = 1.4142137000082988; // not sure why this magic number is needed- now working on a "real" solution
projection.scale(scale * 1, scale * .5);

I'm currently trying to get my head around the wiki article.
I see the beta angle is 45, like in the matrix above, but I don't understand  where does the 'magic' number come from, and the connection between the isometric angle and the scale ratio (1,1/2).

If I want to use a custom angle, how do I work out what angle I use instead of 45 ? , what would the scale value and scale ratio be ?


texts: How can auto-click software be detected to stop botting/cheating?

texts:
I have to completely change my question, because it was far too general. I now want to focus on how I can detect one type of cheating method.

How can auto-clicking be detected? In general, I am referring to software that will simulate mouse clicks or keyboard input automatically. It seems this would be useful for botting behaviour.

Can my software see other software the user's computer is running. If so, how does the software know what the other program is doing? Will it need to check the byte code for routines that simulate mouse/keyboard input?

Would it be useful for my software to detect if the mouse is jumping across the screen in a non-human-like behaviour? That is the first thing I can think of to stop it, as it would be the simplest but also the cheater might be able to simulate mouse movement that is human-like.

I should probably mention that I am most comfortable with Python and C++, and I am currently learning the Windows API.


texts: SteamVR Unity Skeleton Pose NullReferenceException

texts:
I'm developing an application using SteamVR in Unity. When running my app, the console keeps getting flooded with hundreds of instances of this error:

NullReferenceException: Object reference not set to an instance of an object
Valve.VR.SteamVR_Action_Boolean.GetState (Valve.VR.SteamVR_Input_Sources inputSource) (at Assets/SteamVR/Input/SteamVR_Action_Boolean.cs:94)
Valve.VR.SteamVR_Skeleton_Poser+PoseBlendingBehaviour.Update (System.Single deltaTime, Valve.VR.SteamVR_Input_Sources inputSource) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:420)
Valve.VR.SteamVR_Skeleton_Poser.ApplyBlenderBehaviours (Valve.VR.SteamVR_Action_Skeleton skeletonAction, Valve.VR.SteamVR_Input_Sources inputSource, Valve.VR.SteamVR_Skeleton_PoseSnapshot snapshot) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:230)
Valve.VR.SteamVR_Skeleton_Poser.UpdatePose (Valve.VR.SteamVR_Action_Skeleton skeletonAction, Valve.VR.SteamVR_Input_Sources inputSource) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:212)
Valve.VR.SteamVR_Skeleton_Poser.GetBlendedPose (Valve.VR.SteamVR_Action_Skeleton skeletonAction, Valve.VR.SteamVR_Input_Sources handType) (at Assets/SteamVR/Input/SteamVR_Skeleton_Poser.cs:177)
Valve.VR.SteamVR_Behaviour_Skeleton.CopyBonePositions (UnityEngine.Vector3[] positionBuffer) (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:784)
Valve.VR.SteamVR_Behaviour_Skeleton.UpdateSkeletonTransforms () (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:619)
Valve.VR.SteamVR_Behaviour_Skeleton.UpdateSkeleton () (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:382)
Valve.VR.SteamVR_Behaviour_Skeleton.SteamVR_Input_OnSkeletonsUpdated (System.Boolean skipSendingEvents) (at Assets/SteamVR/Input/SteamVR_Behaviour_Skeleton.cs:358)
Valve.VR.SteamVR_Input.UpdateSkeletonActions (System.Boolean skipSendingEvents) (at Assets/SteamVR/Input/SteamVR_Input.cs:360)
Valve.VR.SteamVR_Input.UpdateVisualActions (System.Boolean skipStateAndEventUpdates) (at Assets/SteamVR/Input/SteamVR_Input.cs:320)
Valve.VR.SteamVR_Input.OnPreCull () (at Assets/SteamVR/Input/SteamVR_Input.cs:303)
Valve.VR.SteamVR_Behaviour.PreCull () (at Assets/SteamVR/Scripts/SteamVR_Behaviour.cs:219)
Valve.VR.SteamVR_Behaviour.OnBeforeRender () (at Assets/SteamVR/Scripts/SteamVR_Behaviour.cs:189)
UnityEngine.BeforeRenderHelper.Invoke () (at C:/buildslave/unity/build/Runtime/Export/BeforeRenderHelper.cs:105)
UnityEngine.Application.InvokeOnBeforeRender () (at C:/buildslave/unity/build/Runtime/Export/Application.cs:324)

I do not understand the error. I have my project's SteamVR input settings configured to their defaults, and the skeleton interaction on the HTC Vive controllers act normally.

What is this error trying to tell me and how can I fix the issue?

Thank you for your help!