texts: Drawing multiple objects from one Vertex Buffer Object in OpenGL/OpenTK

texts:
I am trying to experimenting drawing method using VBO in OpenGL. Many people normally use 1 vbo to store one object data array. I was trying to do something quite opposite which is storing multiple object data into 1 vbo then drawing it. There is story behind why i want to do this. I want to group many of objects as a single object sometime. However my code doesn't do the justice. Following is my pseudo code:

//Data
int[] _vBO = new int[1]; //vertex buffer objects

_triangleVertices = new float[]
                  { 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, //first triangle lineloop, positions in the middle of the screen.
                    3.0f, 1.0f, 0.0f, 2.0f, -1.0f, 0.0f, 4.0f, -1.0f, 0.0f, //second triangle lineloop, positions on the left side of the first triangle.
                    -3.0f, 1.0f, 0.0f, -4.0f, -1.0f, 0.0f, -2.0f, -1.0f, 0.0f  }; //third triangle lineloop, positions on the right side of the first triangle.

//Setting Up
void init()
{
   GL.GenBuffers(1, _vBO);
   GL.BindBuffer(BufferTarget.ArrayBuffer, _vBO[0]);
   GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(sizeof(float) * _triangleVertices.Length), _triangleVertices, BufferUsageHint.StaticDraw);
   GL.VertexPointer(3, VertexPointerType.Float, 0, 0);
   GL.EnableClientState(Array.VertexArray);
}

//Drawing
void display()
{
    GL.Clear(ClearBufferMask.ColorBufferBit);
    GL.Clear(ClearBufferMask.DepthBufferBit);

    //setting up camera and projection.
    float[] eyes = { 0.0f, 0.0f, -10.0f };
    float[] target = { 0.0f, 0.0f, 0.0f };
    Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(0.785398163f, 4.0f / 3.0f, 0.1f, 100f);  //45 degree = 0.785398163 rads
    Matrix4 view = Matrix4.LookAt(eyes[0], eyes[1], eyes[2], target[0], target[1], target[2], 0, 1, 0);
    Matrix4 model = Matrix4.Identity;
    Matrix4 MV = view * model;

    GL.MatrixMode(MatrixMode.Projection);
    GL.LoadIdentity();
    GL.LoadMatrix(ref projection);

    GL.MatrixMode(MatrixMode.Modelview);
    GL.LoadIdentity();
    GL.LoadMatrix(ref MV);

    GL.Viewport(0, 0, glControlWindow.Width, glControlWindow.Height);
    GL.Enable(EnableCap.DepthTest); //Enable correct Z Drawings
    GL.DepthFunc(DepthFunction.Less); //Enable correct Z Drawings
    GL.MatrixMode(MatrixMode.Modelview);

    //Draw
    drawTriangleLineLoops();

    //Finally...
    GraphicsContext.CurrentContext.VSync = true; //Caps frame rate as to not over run GPU
    glControlWindow.SwapBuffers(); //Takes from the 'GL' and puts into control
}

void drawTriangleLineLoops()
{
   GL.BindBuffer(BufferTarget.ArrayBuffer, _vBO[0]);
   GL.VertexPointer(3, VertexPointerType.Float, 0, 0);
   GL.EnableClientState(ArrayCap.VertexArray);
   GL.DrawArrays(BeginMode.LineLoop, 0, 3); //drawing first triangle lineloop, first vertex starts at index 0.
   GL.DrawArrays(BeginMode.LineLoop, 9, 3); //drawing second triangle lineloop, first vertex starts at index 9.
   GL.DrawArrays(BeginMode.LineLoop, 18, 3); //drawing third triangle lineloop, first vertex starts at index 18.
   GL.DisableClientState(ArrayCap.VertexArray);
}

I expect 3 different triangles to be drawn, but only one was drawn. I don't know what went wrong.


texts: Is this process for generating an OpenGL perspective projection correct?

texts:
I have been programming OpenGL for a while now and I have successfully created a perspective camera, however, I can't help but shake the feeling that I am doing it wrong. The code I am using is below, is there something wrong with how I am constructing the perspective projection?

int MainWindow_SDL::execute(QCoreApplication &app)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    glewInit();

    // ...

    glLoadIdentity();
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_MODELVIEW);
    glDisable(GL_LIGHTING);
    gluPerspective(50, 1.33, 1, 1000);
    gluLookAt(3, m_xAxisLocation, 4, 0, 0, 0, 0, 1, 0);
    glewExperimental = GL_TRUE;

    // ...

    GameStart();
    app.exit();

    return 0;
}

I also set it up in the game loop:

void MainWindow_SDL::GameLoop()
{
    OpenGLRenderer t_renderer;
    t_renderer.PreGameRender();

    while (m_state == GameState::RUNNING)
    {
        glPushMatrix();
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glLoadIdentity();
        processInput();
        glMatrixMode(GL_MODELVIEW);
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_DEPTH_TEST);
        gluPerspective(50, 1.33, 1, 1000);
        gluLookAt(m_xAxisLocation, m_yAxisLocation, m_zAxisLocation,
                  0, 0, 0, 0, 1, 0);

        t_renderer.DuringGameRender();

        SDL_GL_SwapWindow(m_window);
        glPopMatrix();
    }

    t_renderer.PostGameRender();

    GameEnd();
}


texts: collision resolve sphere-aabb and aabb-aabb

texts:
I am currently working on a basic physics engine which does not consider rotations.
At the moment I work on collision resolving between aabbs and spheres.
Unfortunately I have no idea what a collision between a dynamic aabb and a dynamic sphere looks like.
When a sphere hits a falling aabb from a diagonal direction from above will the aabb be pushed to the sides according to the flight direction of the sphere or only accelerated further downwards?
Also, when the sphere has a certain force, it will not bounce off the aabb but push it in front of itself. I don't know how to deal with this either.

At the moment I have the sphere-sphere collision implemented, which is described here:
http://www.gamasutra.com/view/feature/131424/pool_hall_lessons_fast_accurate_.php?page=3

I guess my solution will be similar, but without caring about the distance between the objects.
Also I guess that the collision resolving of aabb-aabb will be the same as sphere-aabb.

Does anybody have an idea or any experience with collision resolving between aabb-sphere and aabb-aabb?


texts: How do I write a game server with single-threaded networking?

texts:
I want to write a game server with one thread for clients message handling and use something like epoll to accept network messages. All I/O and database access will be processed in a thread pool and they are asynchronous and non-blocking.

Given such a scheme, how should I handle other events/messages (physics, game logic, etc)? Can I implement methods to handle these messages as a blocking interface in the main thread?

What simple, popular servers exist (using Cocos*d/Unity as client) that I could look at for an example of this?


texts: Bullet Collision Shape doesn't wrap Model correctly

texts:
i got an object called human and an object called platform.

I simply let the human fall down on the platform with a constant speed. No acceleration!

The problem is that my collision shapes for both (i use btBoxShape to keep it simple) objects are not wrapping the associated object accordingly:

i scaled it up in paint, sorry for the bad resolution

I got this result calculating the bounds for the model, retrieve the dimensions and the center and then i create a btBoxShape with half of the dimensions and add it to the collisionObject:

box = new BoundingBox();
this.calculateBoundingBox(box);
box.getCenter(center);
box.getDimensions(dimensions);
collisionObject = new btCollisionObject();
boxShape = new btBoxShape(dimensions.sub(dimensions.x/2f, dimensions.y/2f, dimensions.z/2f));
collisionObject.setCollisionShape(boxShape);

And then i set the worldTransforms of the collisionObject to the transform of the object to be drawn(for instance human):

instances.get(0).collisionObject.setWorldTransform(instances.get(0).transform);

So how can i make the collisionShape wrap model?

This is the human in Blender:

I appreciate any help.

Thanks in advance


texts: how can i start mipmap technic from character?

texts:
hi how can i start mipmap technic from character ? i mean example like this picture :

in my code mipmap starts from camera(Near Clipping Plane). i dont want this.

glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,img2->w,img2->h,0,GL_RGBA, GL_UNSIGNED_INT_8_8_8_8,img2->pixels);

glGenerateMipmap(GL_TEXTURE_2D);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

can i make it with use these :
GL_TEXTURE_BASE_LEVEL
GL_TEXTURE_MAX_LEVEL

?
sorry for bad english :) please help me


texts: How can I render primitives to pixel coordinates?

texts:
I'll emphasize that I am very new to graphics programming. I've been using XNA up until now and I've been looking for a way to build simple 2D functionality with textured quads. I'm sort of starting to get how the whole process works, but the idea of positioning things from 0 to 1 doesn't seem quite right for what I'm doing. Is this the only way to do it? I've learned that I'm supposed to be rendering quads to an orthogonal projection, but I guess my problem is exactly how to implement that the correct way.

I totally acknowledge that my problems are a result of not understanding the technology, but all of the tutorials I can find tend to gloss over a lot of the details. Is there a simple way to set up an orthogonal projection in d3d11, and is there a simple way to convert the coordinates so I can specify it in pixels (like the XNA spritebatch)? I'm hoping that seeing the answer to this will help me get a more solid grasp on a lot of the areas where I'm confused in general with graphics programming.


texts:
I am currently working on a game and it is all going well.
On the shop screen there are several buttons that affect the player's stats for when the player restarts the game.

The button's names (with a text on the left), however, are rather cryptic and it's hard to figure out what they do unless you test or something.

So the solution I came up with, is to create an InfoBox with an InfoText inside so that when the cursor is over the button it appears with the description, cost and etc.

This I managed to do too however, the way I was about to do it would mean that I had to create 3 event listeners per button (CLICK, ROLL_OVER, ROLL_OUT) and, obviously, 3 functions connected to each event listener.

Now, I don't mind much about having 1 event listener per button, for the click, but since the other events are just to make a box appear and disappear as well as display some text, I thought it was way too much of a mess of code.

What I tried to do: I created a new class called InfoBoxButton, and this is the class' code:
    package  {

import flash.display.SimpleButton;
import flash.display.MovieClip;
import flash.ui.Mouse;
import flash.events.MouseEvent;

public class InfoBoxButton extends SimpleButton
{
    public var description:String;
    public var infoBox:InfoBox;

    public function InfoBoxButton(description)
    {
        this.addEventListener( MouseEvent.ROLL_OVER, displayInfoText, false, 0, true);
        this.addEventListener( MouseEvent.ROLL_OUT, hideInfoText, false, 0, true);
    }

    private function displayInfoText()
    {
        infoBox.infoText.text = description;
        infoBox.visible = true;
    }

    private function hideInfoText()
    {
        infoBox.infoText.text = "";
        infoBox.visible = false;
    }
}

}

But now I don't have an idea how to associate it with the button, I have tried this:
    public var SoonButton:InfoBoxButton = new InfoBoxButton("This is merely a test");

The SoonButton is a button I made on the shopscreen, SoonButton is it's instance name, but I can't think of a way of associating one button to the other... I have been fiddling with the code for like 3 hours yesterday and no luck... can anyone give me some pointers on how I should go about doing it?

--EDIT--

I tried to trace the SoonButton after it is created like this:
    public var SoonButton:InfoBoxButton = new InfoBoxButton("This is merely a test");

    trace(SoonButton, "whut?");

and I got an error saying:
    1120: Access of undefined property SoonButton.

if I separeted the first line a bit to:
    public var SoonButton:InfoBoxButton;
    SoonButton = new InfoBoxButton("This is merely a test");

    trace(SoonButton, "whut?");

I would get the same error but two times, for each SoonButton... so clearly it must be the InfoBoxButton that isn't being created... what am I missing?


texts: Calculating an orbit and approach velocties

texts: I have drones in my game that need to approach and orbit a node and shoot at it. Problem is I want to stay away from a real physics simulation, meaning I don't want to give the node and drone a mass and the drone's thrusters' a force. I just want to find the best way to approach and then enter orbit. There was a pretty good answer about using bezier curves and doing it that way, but that is essentially a tween between two fixed points. The nodes are also moving as the drones enter orbit.


texts: How do I store and handle time in social game?

texts:
I intend to develop a social game on flash like farmville. I have got a problem in event time handling though.
For Example, if I breed a horse in game and I don't feed it every hour then its health points will decrease. If I log out of the game for 3 days, when I log in again the horse will be dead. I was thinking I would save the last time the user fed the horse in a database, then when the user logs in again I will compare the current time with the time stored in the database.

The problem is, I think this is not an efficient way of doing it. Can anyone show me a more efficient way of doing that?

I'd appreciate anyone who could show me a way.


texts: Creating a 2D game on the X-Z plane instead of the X-Y plane in Unity, any adverse effects or challenges with this?

texts:
After coming to the realization that some things I wish to do in a 2D RTS are easier to do on the X-Z plane instead of the default X-Y plane, I'm considering moving my game over to the other plane.

What I am wondering, past the scripting changes to accommodate the different plane, is what specific challenges will this cause for a 2D game (using 3d physics, not 2d physics)? I did a test and flipped some assets to the X-Z plane and things seemed to work just fine, though I am not sure what unique challenges I will end up facing are.

All our objects will have a 90 degree X-Axis rotation so that their sprites display.


texts: How to resolve collision between a dynamic AABB and static AABB?

texts:
I wanted to ask, how do I resolve collision between 2 cubes - in my case I want to push a moving / dynamic cube (used for the player) out of another static cube (used for the floor or objects in the scene)?

I tried various things, but in the end I don't know how to make the dynamic cube stay smoothly on top of the floor or not able to go through other objects
(everything AABB vs AABB for now).

Below are the most important snippets to understand my problem better.

From PhysicsEngine.cpp

IntersectData intersectData =
                m_objects[i]->getCollider().intersect(
                    m_objects[j]->getCollider());

                // if they intersect, reverse movement to have solid box collisions.
                if(intersectData.getDoesIntersect())
                {
                    // revert movement (later push?) collision response.
                    glm::vec3 diff = m_objects[i]->getPosition() - m_objects[j]->getPosition();
                    glm::vec3 sep = glm::normalize(intersectData.getDirection()) * diff;
                    // std::cout << "Separation between: " << m_objects[i]->

                    // if testCollisionResponse - push back.
                    if (m_objects[i]->testCollisionResponse)
                    {
                        m_objects[i]->setPosition(m_objects[i]->getPosition() + sep);
                        // m_objects[i]->setVelocity(glm::vec3(0.0));
                        // m_objects[i]->testGravity = false;
                        // m_objects[i]->testGravity = false;
                    }
                    else if (m_objects[j]->testCollisionResponse)
                    {
                        m_objects[j]->setPosition(m_objects[j]->getPosition() - sep);
                        // m_objects[j]->setVelocity(glm::vec3(0.0));
                        // m_objects[j]->testGravity = false;
                    }
                }

AABB.cpp

uGE::IntersectData uGE::AABB::intersectAABB(const AABB& other) const

{
    glm::vec3 distances1 = other.getMinExtents() - m_maxExtents;

// test the other way around.
glm::vec3 distances2 = m_minExtents - other.getMaxExtents();

// pick the biggest values between the vectors on each axis.
glm::vec3 distancesOnEachAxis = glm::max(distances1, distances2);

float maxDistance = distancesOnEachAxis[0];
for (int i = 0; i < 3; i++)
{
    if (distancesOnEachAxis[i] > maxDistance)
    {
        maxDistance = distancesOnEachAxis[i];
    }
}

return uGE::IntersectData(maxDistance < 0, distancesOnEachAxis);

}

IntersectData.hpp

class IntersectData

{
public:
    IntersectData(const bool doesIntersect, const glm::vec3 direction) :
        m_doesIntersect(doesIntersect),
        m_direction(direction) {}

inline bool getDoesIntersect() const { return m_doesIntersect; }
inline float getDistance() const { return glm::length(m_direction); }
inline const glm::vec3 getDirection() const { return m_direction; }

private:
    const bool m_doesIntersect;
    const glm::vec3 m_direction;
};

These are the project files (if you want to see more): https://github.com/BigThinker/CPPGame/blob/master/uGE/uGE/Physics/PhysicsEngine.cpp

All the best,
Aldo


texts:
I'm trying to create a preload, but i don't know how to implement the code of this topic in cocos2d iphone v3. Since CCTextureCache has changed to CCTexture, and doesn't have sharedTextureCache property anymore.

@interface TextureHelper : NSObject
+ (void) preloadTextures;
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName;
@end

@implementation TextureHelper
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName {
    return [[CCTextureCache sharedTextureCache] textureForKey:imageName];
}

+ (void) preloadTextures {
    // or could read from a directory...
    NSArray *imageNames = @[
    @"myImage1.png",
    @"myImage2.png"
    ];

    for (NSString *imageName in imageNames)
        [[CCTextureCache sharedTextureCache] addImage:imageName];
}
@end


texts: AS3 Internal preloader (one swf) for flash game with Embeded() images?

texts:
So I am using the Flash IDE.

And I am trying to make a preloader on Frame 1 so that it displays and loads progress before anything else is exported/loaded. So all my assets from the Library are on Frame 2 and all Actionscript Code is Exported in Frame 2.

But my Main Document class calls on other external classes that have Embeded images. Which are then exported in the First frame, which causes my game file to be huge in the First frame. And that essentially shows a white screen for a loong time before the preloader eventually shows up, but 60% loaded.

Is there a way to put the embeded images load later? (as in they would start loading in frame 2)

[Slightly offtopic: I had an idea that I might import the images manually (its a tilesheet and a background image) to the Library. And then copypixel from the tilesheet. But I have never done this so I wouldnt know how to copypixel from something in the library]


texts:
I have open Unity today with a weird bug happening. I can see pixelated noise (I don't know what else to call it), and restarting Unity or my Mac does not work. What can I do? It doesn't affect the game, this just shows in the Scene.

EDIT:

It indeed seems that it has something to do with the camera GameObject; when I remove the Camera the problem goes away. Re-creating the camera does not solve the problem.

It seems the problem goes away when setting the Camera setting "HDR" to "Off", but that still doesn't explain why it happens in the first place.


texts: Not able to change Rigidbody 2d gravity scale

texts:
I have been trying to change the gravity scale of my Rigidbody2d when I click on it. By default it is by 0 and when I click on it, it should change to 1, so that it falls down. I have a square with a boxcollider2d and a Rigidbody2d and a square with just a box collider.

public bool gravity = false;
public bool m_isRunning = false;
public SpriteRenderer m_spriteRenderer;
private Rigidbody2D rb;

private void Update()
{
    if (gravity)
    {
        rb.gravityScale *= -1;
    }
}

private void Start()
{
    m_spriteRenderer = this.GetComponent<SpriteRenderer>();
    rb = GetComponent<Rigidbody2D>();
}

private IEnumerator Changecolor()
{
    yield return new WaitForSeconds(1);
    int random = Random.Range(1, 4);

    if (random == 1)
    {
        m_spriteRenderer.color = Color.blue;
    }
    else if (random == 2)
    {
        m_spriteRenderer.color = Color.red;
    }
    else if (random == 3)
    {
        m_spriteRenderer.color = Color.green;
    }
    else
    {
        m_spriteRenderer.color = Color.yellow;
    }

    this.StartCoroutine("Changecolor", 3f);
}

private void OnMouseDown()
{
    gravity = true;
    m_isRunning = !m_isRunning;

    if (m_isRunning)
    {
        StartCoroutine("Changecolor", 3f);
    }
    else
    {
        StopCoroutine("Changecolor");
    }
}


texts:
I'm interested in how strategic AI engines work, e.g. how to evaluate where to place troops in a turnbased strategy game etc.

I do get how goal based AI works, and I guess that is a good approach to decide what to build or research in a game like Civilization.

But tactical/strategical positioning of troops/units.
What algorithms/strategies are used to evaluate those things? any reference papers/articles?


texts: libgdx, how to check collision of randomly generated actors?

texts:
I have two groups of randomly generated actors, one is bullets second is enemies. And as of now I have no idea how to check collision of randomly genrated actors and remove the overlaped actors. I'm newby.

At least provide some pseudocode! Thanx in advance!!!


texts: Act on Right Mouse Button click on Button

texts: I want to be able to listen for a right mouse click onto a TextButton. Is this possible without removing the default ClickListener of the TextButton? If yes, how? Or should I use a different listener?


texts: Generate and then rasterize vector shape in Monogame/XNA

texts:
I apologize if this is too broad, but I can't seem to find information on this anywhere (perhaps I am searching for the wrong thing?)

Anyways, I'm making a simple game where the player visits different, small, circular planets.  I've successfully made a simple circle texture directly with a for loop, but I've run into a few problems:

How can I easily add variation to the landscape (e.g. Perlin noise)
How can I detect where the surface of the planet is?
How can I easily add objects to the surface of the planet?

I realized that all 3 of these problems could most likely be solved if the planet was generated with a vector polygon.  Noise could be easily applied, and the normal of each edge could help with surface detection/object placement.

However, I could barely find any info on the subject.  Let me be clear - I don't want to directly render a vector shape; I want to invisibly create a semi-random polygon, and then create a filled-in texture based on that convex shape.

Is there any easy way to do this?  Is there a better way to execute this idea in general?


texts:
Getting this error:

  ResolutionException: Cannot find candidate artifact for
  com.google.android.gms:play-services-games:8.1+
  Google.JarResolver.PlayServicesSupport.DependOn (System.String group,
  System.String artifact, System.String version)
  GooglePlayGames.BackgroundResolution.AddDependencies () (at
  Assets/GooglePlayGames/Editor/BackgroundResolution.cs:53)
  GooglePlayGames.BackgroundResolution..cctor () (at
  Assets/GooglePlayGames/Editor/BackgroundResolution.cs:45) Rethrow as
  TypeInitializationException: An exception was thrown by the type
  initializer for GooglePlayGames.BackgroundResolution
  System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor
  (RuntimeTypeHandle type) (at
  /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.CompilerServices/RuntimeHelpers.cs:101)
  UnityEditor.EditorAssemblies.ProcessEditorInitializeOnLoad
  (System.Type type) (at
  C:/buildslave/unity/build/Editor/Mono/EditorAssemblies.cs:123) Rethrow
  as TargetInvocationException: Exception has been thrown by the target
  of an invocation. System.Reflection.MonoCMethod.Invoke (System.Object
  obj, BindingFlags invokeAttr, System.Reflection.Binder binder,
  System.Object[] parameters, System.Globalization.CultureInfo culture)
  (at
  /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:519) System.Reflection.MonoCMethod.Invoke (BindingFlags invokeAttr,
  System.Reflection.Binder binder, System.Object[] parameters,
  System.Globalization.CultureInfo culture) (at
  /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:528) System.Reflection.ConstructorInfo.Invoke (System.Object[] parameters)
  (at
  /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/ConstructorInfo.cs:77)
  System.Activator.CreateInstance (System.Type type, Boolean nonPublic)
  (at
  /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Activator.cs:372) System.Activator.CreateInstance (System.Type type) (at
  /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Activator.cs:254) UnityEditor.AssetPostprocessingInternal.GetMeshProcessorVersions ()
  (at C:/buildslave/unity/build/Editor/Mono/AssetPostprocessor.cs:145)
  UnityEditor.AssetPostprocessingInternal:GetMeshProcessorVersions()

How to solve this?


texts:
I am trying to create a simple game using Amazon Lumberyard and my goal is to have levels/stages where the player will be able to walk around a mini planet.

I have seen a lot of tutorials about this for Unity, but I find it hard to try to translate this into Lua.

My problem is trying to make the "Feet" of the character point towards the planet. Any help would be appreciated.

the script I got for unity is below,

Planet

public class PlanetScript : MonoBehaviour {

public float gravity = -12;

public void Attract(Transform playerTransform)
{
    Vector3 gravityUp = (playerTransform.position - transform.position).normalized;
    Vector3 localUp = playerTransform.up;

    playerTransform.GetComponent<Rigidbody>().AddForce(gravityUp * gravity);

    Quaternion targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * playerTransform.rotation;
    playerTransform.rotation = Quaternion.Slerp(playerTransform.rotation, targetRotation, 50f * Time.deltaTime);
    }
}

and the player has

void FixedUpdate()
{
    if (attractorPlanet)
    {
        attractorPlanet.Attract(playerTransform);
    }
}


texts: Are there any good 2D fighting game engines that can be used to make a commercial product?

texts:
I'm looking for a good 2D fighting game engine based on sprites. I really dont care much about which language that it is programmed in.  Specifically I'm looking for an engine I can use for a game I can sell later and could be exportable to different systems.

Something like 2D Fighter Maker or MUGEN would be great, but that could have a product sold using the tech.


texts: Move camera around player while facing player

texts:
My player has the following hierarchy:

Hero (GameObject)
      Model (child of "Hero", centered at 0-0-0)
      Camera (child of "Hero")

The camera should be allowed to

- change its position around the Model in a circle ("rotate around the
  center")
- rotate so that it always faces the Model
- move up and down
- move nearer and further from / to the Model

I know how to do that using Quaternions, but as I'm doing this in a coroutine and using Lerp, I found myself in situations where the camera would get right through the model as this was the shortest path between the destination and the target vector.

I would now like to use pure angles (Sin and Cos), preferrably without LookAt.
Can somebody share how I would position and rotate the camera according to the angle, perhaps even taking a camera height variable into account as the camera should also be able to move up and down, still facing the player?

That would be the bomb!


texts: How do I scale up pixel art without blur in GM Studio?

texts:
I'm creating a game in Game Maker Studio that uses pixel art.   When I launch the game, all scaled-up textures are really blurry. (It doesn't happen to small ones.)

For example, this image

renders in the game like this:

Is there anyway to resize small pixels into big pixels instead of blurred pixels?


texts: debug unreal engine c++ - how to run in break mode

texts:
I have a number of things not working properly with my FBX imports and I would like to understand how FBX imports work internally. Now, I am noob in software development, so how do I debug the internal C++ code of Unreal? I want to set a breakpoint in Visual Studio Code and explore variables / memory etc. I have found some sources, but for my level of knowledge, they explain nothing to me
To make it clearer: I need to debug internal code, for fbx imports, like not the code that I am writing for my game objects. Basically, I want the engine to stop at the break point once it starts importing fbx (I have found functions seemingly responsible for that)


texts: How can I convert screen coordinatess to world coordinates in OpenTK?

texts:
I'm making a windows forms application with opengl view. I need to get the mouse coords converted to the opengl world coords. Well, my Y coord gets converted wrong. It's hard to explain, so here is the video:
http://tinypic.com/r/23sal8k/6. I'm constantly pressing left mouse button and the red dot should be where the mouse is(but it isn't). Here is the code:

    private void glview_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            Point worldCoords = convertScreenToWorldCoords(e.X, e.Y);
            shitx = worldCoords.X;
            shity = worldCoords.Y;
        }
    }

    // functions:
    public static Point convertScreenToWorldCoords(int x, int y)
    {
        int[] viewport = new int[4];
        Matrix4 modelViewMatrix, projectionMatrix;
        GL.GetFloat(GetPName.ModelviewMatrix, out modelViewMatrix);
        GL.GetFloat(GetPName.ProjectionMatrix, out projectionMatrix);
        GL.GetInteger(GetPName.Viewport, viewport);
        Vector2 mouse;
        mouse.X = x;
        mouse.Y = viewport[3] - y;
        Vector4 vector = UnProject(ref projectionMatrix, modelViewMatrix, new Size(viewport[2], viewport[3]), mouse);
        Point coords = new Point((int)vector.X, (int)vector.Y);
        return coords;
    }
    public static Vector4 UnProject(ref Matrix4 projection, Matrix4 view, Size viewport, Vector2 mouse)
    {
        Vector4 vec;

        vec.X = 2.0f * mouse.X / (float)viewport.Width - 1;
        vec.Y = -(2.0f * mouse.Y / (float)viewport.Height - 1);
        vec.Z = 0;
        vec.W = 1.0f;

        Matrix4 viewInv = Matrix4.Invert(view);
        Matrix4 projInv = Matrix4.Invert(projection);

        Vector4.Transform(ref vec, ref projInv, out vec);
        Vector4.Transform(ref vec, ref viewInv, out vec);

        if (vec.W > float.Epsilon || vec.W < float.Epsilon)
        {
            vec.X /= vec.W;
            vec.Y /= vec.W;
            vec.Z /= vec.W;
        }

        return vec;
    }


texts: How does the SNES' Mode 7 sprite perspective projection work?

texts:
I've always wanted to know how to replicate the old Mode 7 graphics mode of the Super NES. It was frequently used for a pseudo-3D effect in racing games like Top Gear (gameplay video).

Top Gear ⓒ Gremlin Graphics. Image credit: Phil at tasvideos.org.

Every explanation I can find seems a little too complex for me.

In simple terms, how does Mode 7 work?


texts: How can I find a position between 4 vertices in a fragment shader?

texts:
I'm creating a shader with SharpDX (DirectX11 in C#) that takes a segment (2 points) from the output of a Vertex Shader and then passes them to a Geometry Shader, which converts this line into a rectangle (4 points) and assigns the four corners a texture coordinate.

After that I want a Fragment Shader (which recieves the interpolated position and the interpolated texture coordinates) that checks the depth at the "spine of the rectangle" (that is, in the line that passes through the middle of the rectangle.

The problem is I don't know how to extract the position of the corresponding fragment at the spine of the rectangle. This happens because I have the texture coordinates interpolated, but I don't know how to use them to get the fragment I want, because the coordinate system of a) the texture and b) the position of my fragment in screen space are not the same.


texts:
HaxeFlixel has a nifty built-in shader called FlxWaveEffect.

Video
Demo (Flash required) if you start the game and steer the player into an enemy.
Usage (search for FlxWaveEffect)

How does one go about creating a similar effect in LibGDX?


texts:
This must be super-basic, but I don't know where the problem is, since I just started with 3D-Programming.

Why is my model "ballTest" so small on the screen?

private Model _model;
private Matrix view, proj;

//Initialize()
_model = Content.Load<Model>("ball test");
view = Matrix.CreateLookAt(new Vector3(0, 0, 10), new Vector3(0, 0, 0), Vector3.Up);
proj = Matrix.CreateOrthographic(800, 480, 0.1f, 30.0f);

//Draw
_model.Draw(Matrix.Identity, view, proj);


texts: Throttling MonoGame actions (explosions, sounds, etc)

texts:
I'm trying to find a way to deal with throttling/managing actions that need to happen on a regular (regulated) basis.

Right now, if I want to throttle an "action" in MonoGame I need to setup a "timer".

Let's say I want to spawn a bunch of explosions during the update loop, but I don't want to spam them.  I would setup a variable to track the countdown to the next time I can spawn an explosion, and another variable for the time between:

public override void Update(GameTime gameTime)
{
    // ExplosionTimer is a class variable, defaulted to 0
    // ExplosionTimerMax is a class variable set to something like 1000 milliseconds
    ExplosionTimer += elapsedGameTime;

    if (ExplosionTimer >= ExplosionTimerMax)
    {
        // Perform actions
        ExplosionSound.Play();
        SpawnExplosion();

        // Reset the timer
        ExplosionTimer = 0;
    }

    // Other update code
    ...
}

This is pretty easy to setup and straightforward, but is there a better way?  If I need to setup 5 different timers, that means I need to define 10 variables, increment them all, run checks for their state, and reset them if needed.


texts: Is my Lua form/scene loading setup efficient?

texts:
At the moment, I'm working on a small game project using LUA and the love2d framework. Using this framework, I've made my own assets (i.e. button images, form images, etc), and using these assets I've been able to make a functional application, but not yet a game. In my project, I plan on having several scenes, and I'm not quite sure whether my method for scene management/switching is efficient/safe to use (safe, as in minimal bugs). So the process I'm using is as follows:

if scene_selector.active_scene == "splash" then
    if sceneSplash.loaded == false then
        sceneSplash.link.load()
        sceneSplash.link.update(dt)
        sceneSplash.link.draw()
        sceneSplash.loaded = true
    else
        sceneSplash.link.update(dt)
    end
elseif scene_selector.active_scene == "menu" then
    if sceneMainmenu.loaded == false then
        sceneMainmenu.link.load()
        sceneMainmenu.link.update(dt)
        sceneMainmenu.link.draw()
        sceneMainmenu.loaded = true
    else
        sceneMainmenu.link.update(dt)
    end
end

where scene_selector is a link to the follow file:

    -- Misc Vars
    active_scene = "splash"
    version = nil

    -- Resources
    cre = nil
    xp = nil

    -- End Vars

    -- Global Script Indicator
    calls = {}
    calls.active_scene = active_scene
    calls.version = version
    return calls

and sceneSplash/sceneMainMenu are links to lua files which act as the scenes. Each file manages its own updates, which are passed through by the main.lua - found by the love.update and love.draw functions which are passed through to the forms relevant load/update/draw functions. I'm aiming at using about 10 forms, 3 variable files and 2 misc function files (file management/encryption/IO operations/logging/etc).

So the TL;DR version is - is it efficient/safe (safe in terms of minimal bugs) to pass through draw and update functions from main.lua to other lua script files?

So far, the process works without any bugs, even when I go back to a previously accessed 'scene', so I assume the process will work 'safely' when I'm using more scenes.


texts: Is it worth planning to be cross-platform in mobile game development?

texts:
Disclaimer: my goal is not to use cross-platform frameworks like Unity.

I am currently planning a mobile game which I intend to first launch on iOS.  However, I am wondering if it is better to write everything in Objective-C, thus locking the code into the platform, and to do a complete rewrite for other platforms (ie: Android).  The other option would be to write the game logic in C or C++ and to only write the code that interfaces with each OS in the preferred language (Objective-C(++) or Java).

I understand that this must depend on the size of the code base, so what program size should mark the separation?
Finally, if I write cross-platform code, should I stick to C (since Objective-C is a superset of C, making it easy to use C and to use the code samples and because the NDK and the JNI interfaces are more C oriented)? The only advantage I see with C++ in that case is the fact that it is object-oriented and thus it is easier to represent game entities).


texts: Unity, Which side of Collider2D was hit by raycast?

texts: I've got a player firing out 2d raycasts. If one of them hits a boxcollider2d I would like to know if it hit the top side, bottom side, left side, or right side. How would I go about doing this? I've tried using Bounds but that didn't work out very well.


texts: TurnBasedGame with libGDX + Google Play Services

texts:
I'm trying to write a small card game for Android using libgdx framework. My game is turn-based. I wrote to interface with the necessary methods to access the API interface from Google. I faced the problem after I called Games.TurnBasedMultiplayer.createMatch(gameHelper.getApiClient(), tbmc) I got the result of the callback. If initiateMatchResult.getMatch().getData() is null I am initiating games data, and here's the PROBLEM: I don't know how to go back in GameScreen???

This is piece of code in AndroidLauncher:

Games.TurnBasedMultiplayer
                .createMatch(gameHelper.getApiClient(), tbmc)
                .setResultCallback(new ResultCallback<TurnBasedMultiplayer.InitiateMatchResult>() {
                    @Override
                    public void onResult(@NonNull TurnBasedMultiplayer.InitiateMatchResult initiateMatchResult) {
                        if (!initiateMatchResult.getStatus().isSuccess()) {
                            gameHelper.showFailureDialog();
                            return;
                        }
                        TurnBasedMatch match = initiateMatchResult.getMatch();

                        if (match.getData() != null) {
                            Log.d("MyLogs", "match: not null");
                        }
                        initGame();
                        myGame.setScreen(myGame);
                    }
                });

If just call myGame.setScreen(new GameScreen(myGame)) is the GameScreen displaying is not correct. In GameScreen I have table and images in this table and the images displaying is not correct!!!

This code of my GameScreen

public class GameScreen implements Screen {

final MyGame myGame;
private Stage stage;
private Table table;
private Image card1, card2, card3, card4, card5, card6;

public GameScreen(MyGame myGame) {
    this.myGame = myGame;

    stage = new Stage();
    Gdx.input.setInputProcessor(stage);

    card1 = new Image(new Texture(Gdx.files.internal("1.png")));
    card2 = new Image(new Texture(Gdx.files.internal("2.png")));
    card3 = new Image(new Texture(Gdx.files.internal("3.png")));
    card4 = new Image(new Texture(Gdx.files.internal("4.png")));
    card5 = new Image(new Texture(Gdx.files.internal("5.png")));
    card6 = new Image(new Texture(Gdx.files.internal("6.png")));

    table = new Table();
    table.setFillParent(true);
    table.setDebug(true);
    table.add(card1).width(140).height(202).padLeft(15).padRight(15).padBottom(10);
    table.add(card2).width(140).height(202).padBottom(10);
    table.add(card3).width(140).height(202).padLeft(15).padRight(15).padBottom(10).row();
    table.add(card4).width(140).height(202).padLeft(15).padRight(15);
    table.add(card5).width(140).height(202);
    table.add(card6).width(140).height(202).padLeft(15).padRight(15).row();

    stage.addActor(table);
}

@Override
public void show() {

}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.act(delta);
    stage.draw();
}

@Override
public void resize(int width, int height) {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {
    stage.dispose();
    mySkin.dispose();
    dixit.getScreen().dispose();
}

SCREENSHOT BELOW

this screenshot shows how to display images in my table
Tell me what my mistake and what am I doing wrong? Can anyone advise how best to do otherwise??


texts: How do I pause Andengine, but still get input?

texts:
In my game when I pause the game, I'd like to display three options (Resume, Restart and Menu) so I did this after calling mEngine.stop():

Sprite resume = new Sprite(CAMERA_WIDTH/2, CAMERA_HEIGHT/2, RM.resume, vertex){
            @Override
            public boolean onAreaTouched(TouchEvent event, float pTouchAreaLocalX, float pTouchAreaLocalY) {
                if(event.isActionDown()){
                    this.setScale(1.1f);
                    Log.i("Click","Click");

                }

                return super.onAreaTouched(event, pTouchAreaLocalX, pTouchAreaLocalY);
            }
        };

But the Log "Click" never display. So I tried to do this with the Engine active and the Log displays correctly.

How can I stop my game (Modifier, Physics, Score) without using the mEngine.stop() method ?


texts: Floor is moving faster than ball above it , and it causes ball to fall off the map. UE4

texts:
I am creating a game ( following Udemy lesson on Marble run) which is basically a maze and ball and we move ball my rotating floor on x or y axis through obstacles .
Floor movement is linked on Mouse values.
BP

My problem is if I move my mouse too fast ball comes below floor and drops.
I know there could be multiple hacks to solve this . but I am looking for best solution ( professional solution) I am a newbie so please bear with me :)
Below is screenshot of ball below maze


texts: unity and maya - how to export/import fbx animation with rootmotion and non-rootmotion clips?

texts:
I've started learning about and playing around with animations in Unity and I've installed the Basic Motions Pack by Kevin Iglesias. I wanted to know how they work and to see if I can modify them so I've looked at the animation files which are .fbx. The animation hierarchy in Unity looks like this

where BasicMotions@Walk01 is the in-place animation and [RootMotion] is the root motion variant which has velocity. I've looked into what root motions are and I think I've grasped what they are, but here's where things have gotten interesting.
I've imported the BasicMotions@Walk01.fbx into Maya and it looks like this

it has a root joint for root motion and the animation moves the rig in each keyframe. So far so good! I've modified the animation so that it plays in reverse, basically made a sketchy reverse walk animation. Exported it to .fbx with the following parameters

And then opened that in Unity, however when I import the animation and rig it it only has one clip and it's the Root motion clip, and I can't get the non-rootmotion clip.
The Root Transform Position (XZ) Loop match is always red and if I don't bake it into pose the animation functions like the Kevin's RootMotion animations, but I don't know how to get the non-RootMotion clip. What am I doing wrong here?


texts:
I'm working on a roguelike and attempting to write the message system. When I attempt to format a const char* with vsnprintf, it seems to somehow format it incorrectly to the point where it is corrupted.

void Gui::render()
{
    for(auto iter = log.begin(); iter != log.end(); iter++)
    {
        terminal_printf(1, 45, (*iter));
    }
}

void Gui::message(const char *text, ...)
{
    char buffer[256];
    va_list argptr;
    va_start(argptr, text);
    vsnprintf(buffer, 256, text, argptr);
    va_end(argptr);
    log.emplace(log.begin(), buffer);
}

If I call puts() in message() with buffer as an argument after it has been formatted, it is correctly formatted. If I directly emplace the text, it isn't corrupted, but it obviously isn't formatted. If puts is called in the iteration loop on the iterator, it outputs the corrupted data.


texts: GLSL Light (Attenuation, Color and intensity) formula

texts:
I'm implementing point lights in my Voxel engine, and I'm really struggling to get a good flow of light, from 100% near the light source to 0% at the light radius.

I have 5 arguments for the function:

Light color (Vec3)
Light intensity (distance from the light till the distance where falloff is 100%)
Distance from the light to the fragment
The angle from the fragment normal to the light
The position of the light

Can anyone push me in the right direction to create a function for the calculating of the fragment color?

Image of one of my experiments:

Edit (current code requested by Byte) Note that this is just some experiment code from my side. I got the float att from a website, and it kinds works, but far from perfect.:

void main()
{
// Light color
vec3 torchColor = vec3(1.0f, 1.0f, 1.0f);

float lightAdd = 0.0f;
for (int i=0; i<5; i++) {
    vec3 pos = lights[i];
    if (pos.x == 0.0f) continue;

    float dist = distance(vertex_pos, pos);
    if (dist < 9) {
        float att=1.0/(1.0+0.1*dist+0.01*dist*dist);
        vec3 surf2light = normalize(pos - vertex_pos);
        vec3 norm = normalize(normal);
        float dcont=max(0.0,dot(norm,surf2light));
        lightAdd += att*(dcont+0.4);
    }
}

vec3 textureColor = texture2D(texture, texture_coordinate).rgb;
vec3 torch_output = lightAdd * torchColor;

vec3 final_color = ((0.1+torch_output) * textureColor);

gl_FragColor = vec4(final_color, 1.0f);
}


texts: Cocos2d: Tongue effect like in Munch Time

texts:
I'm wanting to do a tongue effect for my character like the one in Munch Time( shown in pic ). The player does some action and his tongue attaches to the nearest platform.

I'm thinking this is simply a get distance to platform and keep player at that distance as he moves back and forth giving him the swinging effect.

For the drawing, I'm wanting the same effect where the tongue sprite is the skinniest in the middle of the distance between the character and platform.

I know how to do this in a shader( I'm using cocos2d v2 btw ), but I'm wondering if there is some built-in functionality to allow me to do this.

First, is this the right approach using distance?

Second, is their an easy way to do the tongue sprite effect without a shader?

Third, I'm wanting to have the player spring up at will in the direction of the platform. I'm using Box2D. Would there be a way to do this using force's or would it be easier to write my own code?


texts: When does a Reference become Copyright Infringement?

texts:
I've seen quite a few posts on here similar to my question, but I am still having doubts about my implementation of an Easter Egg.

In the background of my game, There is a bookshelf, purely for cosmetic purposes. Because it's got books in it, I wanted to have names on all the books, as references to either real-world books, or fictional books in media.

Some Examples:

Real World Books:(These ones all have the authors names included on the cover)

 I-Robot

 D&D Monster Manual

 Rendevous with Rama

Fictional Books:(No Authors, Because they're fictional)

 The Necronomicon (From many H.P Lovercraft Stories)

 The Enchiridion (From Adventure Time)

 Gray's Sports Almanac 1950-2000 (Back to the Future)

Books Imagined by Me:

 Graboid Hunting for Beginers (Graboids are monsters in Tremors, but this book does not exist in the movies)

 Aperature Science Employee Handbook (Aperature Science is the corporation from Portal, but this book does not exist in the games)

So, My question is, is it "acceptable" to simply mention names of real-world or fictional works in a background asset such as this? Or is even that going to far?
My confusion comes from the fact that i'm not using any of the writing or artwork from the works, simply stating the name of the title.

If someone could please give my some guidance on this, I would greatly appreciate it.

Thanks!


texts: Some theory questions about classic endless arcade games

texts:
I had read in the book "A theory of fun for game design" that once the player realizes that he cannot overpower the computer in anyway (or) the AI is unbeatable (badly designed/coded) he will leave the game and not try to beat it. But looking at new age games like "Jetpack Joyride" I think this rule is not true for everyone anymore. Not sure if this is a deliberate choice or just bad design.

I want to know if there exists any history about how the old classic ATARI / Arcade machines games were implemented/tested. Best example would be Pac-man/Asteroids etc. I am hoping that those game makers didn't just increment the speed of the enemies blindly with the level number. They must have tested it enough to ensure that the game can actually beaten up to very high levels and might have tweaked the required parameters to ensure it in their code.

Are there articles/tutorials about designing endless arcade games? I have been searching a lot but couldn't find any.


texts:
I'm currently looking at this phaser example: http://phaser.io/examples/v2/tilemaps/blank-tilemap

Here, the author creates a simple tilemap editor. In line #33 he adds a preloaded image as tileset.

The problem is: the author adds only one tileset but I'd like to add multiple tilesets to the map (via map.addTilesetImage), switch between them and paint with the "current one".

I've read multiple times on the internet that it is possible to add and use many tilesets on a single map, but so far I haven't found any examples of that and the phaser docs also don't give that away.


texts: How to read a custom binary file made with Adobe air into Unity 3D & C#

texts:
I have a custom data file from a project that was authored in actionscript some years ago by another developer.  I am porting parts of the project over to Unity 3D.  I don't have any documentation for the original project (I hope to speak to the original developers at some point but I cannot wait for that).

The file is a special bitmap that represents the positions of objects on a grid.  The custom file is created using an editor created in Adobe air.  I believe (not knowing any better) that the source code I have for the file decoder is the same source from the editor.  I don't have the editor source code.

Where I am getting into trouble is the binary file. From what I can tell at the moment, the file is a compressed byte array on the Adobe air side of things.  I don't believe I can just load the compressed file with Unity3D as a resource object. I would like to decompress the file and use it as an asset in Unity.

I am trying to figure how to decompress the binary file.  I have tried viewing the file contents in a hex editor to establish what the compression format is with no joy; I have not done anything specifically like this before .  I have tried to use gzip and a few other apps to decompress the file.

Form what I have read in the action script documentation that the default compression should be zlib.

Here is some edited code from the original project for decoding the bitmap:

import flash.utils.ByteArray;

public function decode(byteArray:ByteArray):Boolean
    {
        var i:uint;
        var j:uint;

        if(colourMap!=null)
        {
            colourMap.dispose();
            depthMap.dispose();
        }

        byteArray.uncompress();
        byteArray.position=0;

        var fileVersion:String=byteArray.readUTFBytes(FILE_VERSION.length);

        if(fileVersion==FILE_VERSION)
        {
            numWidth=byteArray.readUnsignedInt();
            numHeight=byteArray.readUnsignedInt();

            if(numWidth==0)
            {
                numWidth=30;
                trace("WARNING FOR SOME REASON WIDTH WAS 0 FROM FILE");
            }

            if(numHeight==0)
            {
                numHeight=30;
                trace("WARNING FOR SOME REASON HEIGHT WAS 0 FROM FILE");
            }

Here is a hex dump of the initial part of the binary data file:

78 da ec bd 55 cf 6c 5d 76 a5 79 7c 53 2a ff 8c


texts: Python mini RPG enemy movement. (how to have two infinite loops running at the same time)

texts:
I have a problem with my RPG.

I want enemies to wander randomly. So I put:

enx_speed = random.randint(-2, 2)
eny_speed = random.randint(-2, 2)

in the main loop (while true:).
However, that loops every 20 milliseconds (it's what I use to redraw, find key presses, etc).

How can I have two infinite loops running at the same time with different loop times?


texts:
I am making a sprite based game, and I have a bunch of images that I get in a ridiculously large resolution and I scale them to the desired sprite size (for example 64x64 pixels) before converting them to a game resource, so when draw my sprite inside the game, I don't have to scale it.

However, if I rotate this small sprite inside the game (engine agnostically), some destination pixels will get interpolated, and the sprite will look smudged.

This is of course dependent on the rotation angle as well as the interpolation algorithm, but regardless, there is not enough data to correctly sample a specific destination pixel.

So there are two solutions I can think of. The first is to use the original huge image, rotate it to the desired angles, and then downscale all the reaulting variations, and put them in an atlas, which has the advantage of being quite simple to implement, but naively consumes twice as much sprite space for each rotation (each rotation must be inscribed in a circle whose diameter is the diagonal of the original sprite's rectangle, whose area is twice of that original rectangle, supposing square sprites).

It also has the disadvantage of only having a predefined set of rotations available, which may be okay or not depending on the game.

So the other choice would be to store a larger image, and rotate and downscale while rendering, which leads to my question.

What is the optimal size for this sprite? Optimal meaning that a larger image will have no effect in the resulting image.

This is definitely dependent on the image size, the amount of desired rotations without data loss down to 1/256, which is the minimum representable color difference.

I am looking for a theoretical general answer to this problem, because trying a bunch of sizes may be okay, but is far from optimal.


texts: Swap between first person and eagle eye view cameras, hiding the FP controller

texts:
Not sure what has to be done to correctly swap between a generic fps controller camera, to something like an eagle eye view.

The idea is to have the player use the FPS controller, then when he get in a control seat; I want to switch to a larger view; kinda like a RTS view from the top (I call it "eagle eye", not sure about the technical name).

I did check around and from my research, I have to swap active camera parameter; but when I do so, the FPS remain active, while I would like to hide it, and also disable it completely, since the player will use the mouse at that point.

If I destroy the FPS, that works, but when the player leave the control seat, I have to re-create it, which bring a whole level of pain, to restore its state.

How do you disable temporarily a FPS, so it won't be neither visible nor it will interact with anything?


texts: Deterministic Multiplayer RTS game questions?

texts:
I am working on a cross-platform multiplayer RTS game where the different clients and a server(flash and C#), all need to stay deterministically synchronised.

To deal with Floatpoint inconsistencies, I've come across this method: http://joshblog.net/2007/01/30/flash-floating-point-number-errors/#comment-49912 which basically truncates off the nondeterministic part:

return Math.round(1000 * float) / 1000;

Howewer my concern is that every time there is a division, there is further chance of creating additional floatpoint errors, in essence making it worse?

.

So it occured to me, how about something like this:

function floatSafe(number:Number) : Number
{return Math.round(float* 1024) / 1024; }

ie dividing with only powers of 2 ? What do you think?

.

Ironically with the above method I got less accurate results:

trace(  floatSafe(3/5) ) // 0.599609375

where as with the other method(dividing with 1000), or just tracing the raw value I am getting 3/5 = 0.6

or Maybe thats what 3/5 actually is, IE 0.6 cannot really be represented with a floatpoint datatype, and would be more consistent across different platforms?


texts: Sharing VBO with multiple objects and fixed size buffer data

texts:
I'm just messing around with OpenGL and getting some basic structures in place and my first attempt resulted in each SceneObject class (just contains vertex information right now) having it's own VBO inside it, however I've read that it might be better to share VBOs across multiple objects.

Also, I read that you should avoid resizing a VBO (repeated calls to glBufferData with different size parameters), and instead choose a fixed size for a VBO, and just try a range from the buffer. I don't think changing the size of the buffer data would happen too often, but surely it would be better to only allocate the data you need? Choosing an arbitrary value seems risky.

I'm looking for some advice on working with individual objects in a scene and their associated buffer data.


texts: Circle to Circle collision - bad accuracy

texts:
Circle1 (blue) is moving and its X and Y bounds are the screen (meaning it bounces off the walls).

Circle2 (black) is stationary. Circle1(blue) is supposed to bounce off of Circle2 without intersecting, regardless of the collision point. As you can see on the image below, the blue circle bounces off properly only at the blue arrow spots, otherwise(red arrows), blue ball goes INSIDE the black circle, gets stuck in there for a second and then gets out.

I have no idea why this is happening. Please take a look at my code and help me out.
Thanks.

public void handle(ActionEvent t) {
                if (counter++ % 5 == 0) {
                    // Moves the ball depending on the values of X and Y
                    circle.setLayoutX(circle.getLayoutX() + X); //velocity
                    circle.setLayoutY(circle.getLayoutY() + Y); //velocity

// Bounce off the walls (working perfectly)
                    final Bounds bounds = canvas.getBoundsInLocal();
                    boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
                    boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
                    boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
                    boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());

//THE PROBLEM IS HERE

//Collision between circle1 and circle2 (stationary black circle.
                    double dx = circle.getLayoutX() - circle2.getLayoutX();
                    double dy = circle.getLayoutY() - circle2.getLayoutY();
                    double radii = circle.getRadius() + circle2.getRadius();

                    if ( (dx * dx) + (dy * dy) <= radii * radii) {
                        X = X * -1; //X gets inverted to change direction

                    }

 //The code below is working perfectly.
                    // If the bottom or top wall has been touched, the ball reverses direction.
                    if (bottomWall || topWall) {

                        Y = Y * -1;
                        //circle.setLayoutY(circle.getLayoutY() - 50); - Wasn't working. Had to create X and Y to fix the problem.

                    }
                    // If the left or right wall has been touched, the ball reverses direction.
                    if (leftWall || rightWall) {
                        X = X * -1;
                    }
                }
            }

        }));

        loop.setCycleCount(Timeline.INDEFINITE);
        loop.play();
    }

P.S. Apologies for the amazing paint skills :D


texts: How can a game prevent people from running multiple instances of itself?

texts:
Starcraft II restricts me from running multiple instances, but if I run the second instance sandboxed in Sandboxie, it works. What might account for this?

How might I replicate this behavior for my own games?


texts: How can I save a score for a web game made in Unity and load it when the game starts again?

texts: In other words, how can I load the progress for a game? I only want to store a score and load it again when the game starts (ex. if I get the 100 score and close the game, when I come back, I want to continue my progress from the 100 score)


texts: Handling Player "sessions" on a UDP based server

texts:
I've been building a UDP server and have hit a bit of a stumbling point. Since UDP is not a persisted connection, there really isn't a way for me to track if the Player has left the current session/closed the game etc.

What I was planning on doing was having the server/client perform some kind of handshake when the client first attempts to join a game session. The server would store the server-side Player object and it's associated EndPoint(s) in a collection. This way, when Player A does something that affects Player B, I can update the two player objects on the server-side and send both players updated info.

What happens if Player A closes the game? I need to clean up my collection of Player/Endpoint(s). I'm not sure how that is typically handled. Should I have a timer that runs every minute or two, pinging clients and removing them if no ping comes back? Since It's UDP, I can't assume that "no new datagrams" really means the player isn't playing. It's possible that they've just not needed to send any data for a while (maybe it's paused or something idk). I have a low-overhead async timer API that runs on background threads that I could use, but it feels like a lot of overhead to ping every connected client every couple of minutes.


texts: maya script editor: how to keep python code after execute

texts: see my gif, in script editor, I hope keep python code after code is executed and run it again next time, how should i do?


texts: Finding the closest point of a structure/building that has a path

texts:
I am making an RTS game, and I implemented path finding with A*.
My A* algorithm uses 8 directions and terminates early in the case of no path found (I use 50*the  vector distance between the unit and the point as the limit to dequeueing the fringe).  If there's no path then they will go to the nearest valid point to the destination.  This problem arises because a structure is bigger than 1 tile

I am having trouble now with attacking a structure, right now I have it so that it checks each "tile" of the structure, and gets the distance between the unit and the structure "tile".  Plus, it will see if theres a path from that tile to the unit, and if there is then the tile is  put in a priority queue, where priority is min distance.

Here, this can be a lot of path finding calls for 1 unit using this, the number of calls is dependent on the x*y size of the structure.  Here is a picture to illustrate (with the orange being the unit, red being barrier (that can potentially move) and the blue being the structure)

Here there will be 9 calls to path finder, 8 of them will fail almost immediately , 9 will produce the path from the unit in orange to the bottom right corner of the structure.

It can get much worse with an example like this:

Here there will be 6 path finding calls which could take a long time depending on the space between the unit and the structure.  So there must be a better way to path to a closest available tile of a structure without calling path finder for each tile in the structure and I need help with that.  How would I go about treating the entire blue region as the goal? My node only encompasses one tile, so would I need multiple destinations (so multiple f values)?


texts: Create quaternion based on where a unit is hit (shield effect as in Starcraft 2)

texts:
I'd like to implement a shield effect like that done for Protoss units in Starcraft 2. I'm guessing that the technique involved uses a partial sphere that is rotated to reflect where a unit is hit.

Assuming this is the idea, how can I create a quaternion to rotate this model to achieve the desired effect? My collision detection system conveniently relies on sphere-sphere intersection.

Edit: this is pretty much a dupe of this, which has a pretty thorough answer.


texts: Displaying whole screen image on multiple devices without stretching

texts:
In my(Android) game, all of my sprites are scaled against to a particular ratio (this 'guide' ratio stays the same regardless of the actual ratio of the screen on which they are to be displayed) - these sprites are then displayed on screens of different ratios.

This way, the game can run full screen on any device, it simply means that more/less of the game is visible on some devices than it is on others.

However, I can't work out how to diaplay a large (full-screen) image on different devices.

The only thing I can think of is to simply create the original image for the larger display and the crop it down to fit other ratios.  Something like this:

So here, the image on the right is how the picture will show on the original device (full-screen with no cropping), the device on the left has a smaller width.  But what if this runs on a device with a larger screen?

In this case is it simply a case of (uniformly) stretching the image until it fills the screen?

Would be grateful for some guidance.


texts: Why is it called "roguelike" and "metroidvania"?

texts:
As the title says, where did roguelike and metroidvania genre games get their names from? All other genres (that I can think of) have pretty self-explanatory names like:

First Person Shooter: You shoot and it's first-person perspective.
Role-Playing Game: You role-play as another character.
Massive Multiplayer Online: The game is online with multiplayer and supports a lot of players.

But roguelike and metrodvania doesn't seem to relate to any core gameplay element like the other genres do. So why are they called roguelike and metroidvania?


texts: Can't understand the Schlick model formula

texts:
I'm trying to implement the Schlick shading model in the fragment shader. I took the formulas from Karsten Schwenk's "a survey of shading models for real-time rendering":

First of all I don't understand why there's H and H'. Isn't the halfway vector unique for both layers? It says that just p,r and F vary from layer to layer. But the fragment is the same, so I don't understand how to compute H';
I also don't understand, for how it may seem banal, what does [F D] mean. Is that just a plain multiplication? I don't understand why it uses the bracket square syntax;
To compute D' should I replace p with p' and r with r' ?


texts: How to correctly solve a procedurally generated puzzle?

texts:
I'm creating a puzzle game where the player must remove all colored blocks from a grid. When the player selects a block, all adjacent blocks of the same color are removed. Any blocks that have empty cells below them will then fall into those cells. Here's a simple illustration of the mechanic:
https://imgur.com/TBNrAUW
The game will procedurally generate puzzles with varying degrees of difficulty. When the player completes a puzzle the game will then score the player based on how quickly and, more importantly, how efficiently they solved the puzzle.
The problem I am having is implementing a method of determining the most efficient way of solving a puzzle (i.e. identifying the fewest number of moves possible). Here's an example of a puzzle that was generated:
https://imgur.com/RQcAgkH
As a human, I could identify that the fewest number of moves that could be made to solve this puzzle was 11. Here is a gif of the solve:
https://imgflip.com/gif/463qck
However, when I whipped up an application that just clicked blocks at random in order to solve this puzzle, the lowest number of moves that it was able to solve this in was 14. And this was over billions of iterations which took many minutes. Obviously that is not acceptable. I need to find the correct solution and it should be done within seconds.
I also tried to reverse-engineer the generation process but that doesn't work. For example, it could place a blue block in column 1, a bunch of other blocks, a red block in column 1, a bunch of other blocks, then another blue block in column 1. Column 1 could be resolved in 2 moves (by clicking the red block and then one of the blue blocks), which reverse-engineering the generation would not detect.
So, my question:
What kind of techniques or tricks can I implement that will allow the application to resolve this type of generated puzzle quickly and correctly? I'm sadly out of ideas.


texts: How can I create a game as a live wallpaper?

texts:
I have a space shooter game for Android and I want to implement it as a live wallpaper. Any ideas on how this can be done?

Or better yet can anyone help me / provide a template that calls a "ship" object that fires missile? I'll do the rest from there onwards. I just need it as a starting point for learning Android.


texts: Why is XmlSerializer adding junk to the end of my file?

texts:
I'm making a game and I am serializing the save game data. The data is simply a few lists of bools, ints and floats.

But about 50% of the time I get an error when the data tries to save or load that says "There is an error in XML document." The error is always located at the end of the file, even after it has changed size or I have added other variables.

It appears that very last part of the XML data is getting copied twice. The last line of the XML should read:

</LevelStats>

But when an error occurs it often reads

</LevelStats>>

Or

</LevelStats>tats>

Or some other small part of the last line duplicated.

Here is the class I am serializing:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Xna.Framework.Storage;
using System.IO;

namespace Jetpack.Classes
{
    [Serializable]
    public struct LevelStats
    {
        // Player Bests
        public List<float?> fTimeList;
        public List<int?> iScoreList;
        public List<int?> iFuelList;

        // Time
        public List<bool> bBronzeTimeList;
        public List<bool> bSilverTimeList;
        public List<bool> bGoldTimeList;

        // Score
        public List<bool> bBronzeScoreList;
        public List<bool> bSilverScoreList;
        public List<bool> bGoldScoreList;

        // Fuel
        public List<bool> bBronzeFuelList;
        public List<bool> bSilverFuelList;
        public List<bool> bGoldFuelList;

        // Level Complete
        public List<bool> bIsLevelComplete;
    }
}

And here are my methods for saving the loading the data:

region Save & Load Level Stats
    public static void SaveLevelStats(LevelStats levelStats, string filename)
    {
        // Get the path of the save game
        string fullpath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename);

        // Open the file, creating it if necessary
        FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate);
        try
        {
            // Convert the object to XML data and put it in the stream
            XmlSerializer serializer = new XmlSerializer(typeof(LevelStats));
            serializer.Serialize(stream, levelStats);
        }
        finally
        {
            // Close the file
            stream.Close();
        }
    }

    public static LevelStats LoadLevelStats(string filename)
    {
        LevelStats levelStats;

        // Get the path of the save game
        string fullpath = System.IO.Path.Combine((Directory.GetCurrentDirectory()), filename);

        // Open the file
        FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate,
        FileAccess.Read);
        try
        {
            // Read the data from the file
            XmlSerializer serializer = new XmlSerializer(typeof(LevelStats));
            levelStats = (LevelStats)serializer.Deserialize(stream);
        }
        finally
        {
            // Close the file
            stream.Close();
        }

        return (levelStats);
    }

    #endregion

Why am I getting the error above?


texts: How can I enable Continuous Collision Detection (CCD) in Bullet Physics?


texts: How to animate objects with bobbing up and down motion in Unity?

texts:
I have created a 2D platform game with Unity and C# where I have collectable items that can be picked up by the player. What I want is to give the items more focus by having them bobbing up and down.

I came up with the following version:

Vector2 floatY;

public float FloatStrength; // Set strength in Unity

void Update () {
    floatY = transform.position;
    floatY.y = (Mathf.Sin(Time.time) * FloatStrength);
    transform.position = floatY;
}

But, this makes the object float in the middle of the level instead of where the object is positioned. How can I fix that?

Here is a screenshot of the prototype of the game:

The player can collect the wood stumps which should be bobbing up and down in space just above the ground.


texts: Even though I set ue4editor.exe to use integrated graphics on my laptop, it somehow ends up using the discrete nvidia gpu; is there a way to set the preferred gpu with the unreal suite?


texts:
for (int i = -5; i < 5; i++)
{
    Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);
    spriteBatch.Draw(foregroundTexture, screenRectangle, Color.White);

    Rectangle backGroundRectangle = new Rectangle(x + screenWidth * i, 0, screenWidth, screenHeight);
    spriteBatch.Draw(backgroundTexture, backGroundRectangle, Color.White);

    spriteBatch.DrawString(font, "Variable i:  " + i, new Vector2(0, 0), Color.Brown);
}

I want to show on the screen when I'm running the game the counting of i
like: -5 , -4 , -3...but not in a line, just like a timer. -5 then overwrite it and show -4 overwrite it and show -3 and so on...like seconds of a clock.

The problem is I'm getting a strange painting near the numbers like its repeating and painting something there all the time.


texts: Augment an existing game with touch gestures

texts:
I want to enhance Homeworld 2 gameplay with touch gestures. The game is running on Windows.

So, two questions:

Is it possible to wrap the game with a program that would capture
touch gestures, convert it to keyboard and mouse input and send it
to the game?
How would I approach this task? Using 3rd party libraries, making my own, or something built in to Windows?


texts: How to Prevent Entities Snapping Through Platforms

texts:
I am using crafty.js to make a platformer. I assigned the main player entity the default jumping controls and movement with .twoway() and used .checkHits() against the obstacles ("obs") the player will jump on. The problem is that when the player jumps, if the top of the player entity hits the bottom of the obstacle, the player entity "snaps" to the top. How do I make it so that this movement does not happen? The intended effect is that the player entity will only land on the obstacle if the player entity lands on the top.

Here is the code:

window.onload = function() {

  Crafty.init(600, 400);
  Crafty.background('#07A6FF');

  // obstacle/platform entities
  // 'obs' means obstacle
  var obs = Crafty.e('obs, 2D, DOM, Collision, Color')
  .attr({ x: 100, y: 250, w: 400, h: 45 })
  .color('#E88D0C');

  var obs2 = Crafty.e('obs, 2D, DOM, Collision, Color')
  .attr({ x: 200, y: 150, w: 45, h: 45 })
  .color('#E88D0C');

  // player entity
  var player = Crafty.e('player, 2D, DOM, Color, Collision, Twoway, Gravity, Jumper')
  .attr({x: 50, y: 50, w: 60, h: 40 })
  .color('#0035AB')
  .twoway(200, 150)
  .checkHits('obs')
  .gravityConst(200)
  .gravity('obs');
}
<script src="https://github.com/craftyjs/Crafty/releases/download/0.7.1/crafty.js"></script>


texts: Sprite sheet textures picking up edges of adjacent texture

texts:
I have a custom sprite routine (openGL 2.0) which uses a simple sprite sheet (my textures are arranged horizontally next to each other).
So, for example, here is a test sprite sheet with 2 simple textures:

Now, what I do when creating my openGL sprite object is specify the total number of frames in its atlas and when drawing, specify which frame I want to draw.
It then works out where to grab the texture from by:
Dividing the required frame number by the total number of frames (to get the left coordinate)
And then diving 1 by the total number of frames and adding the result to the left hand coordinate calculated above.
This does seem to work but sometimes I get problems.  Say for example, I want to draw the X below and I get...........

I've heard about putting a 'padding' of 1 px between each texture but could someone explain exactly how this works?  I mean if I do this it will surely throw off the calculations for getting the texture.
If I simple include the padding in texture picked up (so the sprite is drawn with a blank border), then surely this will cause problem with collision detection? (ie sprites may appear to collide when using bounding boxes when the transparent parts collide).
Would appreciate if someone could explain.


texts: Box2dWeb: must fixtures be destroyed explicitly when destroying the body?

texts:
I use b2WorldObj.DestroyBody(bodyObj) to destroy the body when it is not needed anymore. The body has one fixture attached to it.

Do I need to destroy the fixture before destroying the body? or should I assume that by destroying the body all its fixtures will be automatically destroyed?

Right now, I do not destroy the fixtures explicitly and the game runs fine. But my concern is more about memory leaks. I want to make sure that all the bodies and fixtures that are not used anymore are completely removed from the memory. How can I best achieve this?

Thanks!


texts: Drawing a set of VBOs with one draw command in OpenGL. Is there a glMultiDrawElements for VBOs?

texts:
I have a few hundred VBOs, and I want to only draw a subset of the VBOs each frame.

Is there anything faster than binding and drawing each VBO? Is there a batched draw command for multiple VBOs?

How do I bind multiple VBOs?
Is there a version of glMultiDrawElements for sets of VBOs?


texts: Compile shader and root signature of a ray tracing shader into a single binary using DXC

texts:
I'm new to DXR, so please
If I got it right, when we want to compile a ray tracing shader using the DirectX Shader Compiler, we need to specify lib_6_* as the target profile.
Now assume I've got a HLSL file containing a single ray generation shader RayGen whose root signature is specified by a RootSignature attribute of the form
#define MyRS "RootFlags(LOCAL_ROOT_SIGNATURE),"  \
        "DescriptorTable("                  \
            "UAV(u0, numDescriptors = 1),"  \
            "SRV(t0, numDescriptors = 1))"
[rootsignature(MyRS)]
[shader("raygeneration")]
void RayGen() {}

Using IDxcCompiler::Compile, I'm able to compile both the shader itself using the target profile lib_6_3 and the root signature using the target profile rootsig_1_1, but if I got it right it's not possible to invoke IDxcCompiler::Compile such that the created IDxcBlob contains both the shader and the root signature. (I've tried to add the argument -rootsig-define MyRS to the call for the compilation of the shader, but it seems to me that the compiler expects the root signature specified in this way to be a global root signature.)
So, I end up with two IDxcBlob's. Is there any possibility to "merge" them into a single one which can later be used to specify the shader as well in a call of ID3D12Device5::CreateRootSignature?


texts: Multiplayer game sdk for ios and android

texts:
I am working on a multiplayer game supporting Android and IOS.

For IOS Game-Center seems promising. But its IOS only.

OpenFeint could be a option, but now GREE has stopped supporting it.

Is there any other multi-platform SDK which I can use for both IOS and Android?

---------EDIT------

I could not find any good service which provides their own server and SDK for both IOS and android. So finally I chose to go with my own server on AWS-EC2 + python tornado + Websocket. If anyone want to know more plz contact...


texts: Load single texture atlas for multiple sprite

texts:
Recently, I am developing sudoku game. For this, I have created multiple grid 9x9,12x12 and 15x15.

For this numbers are repeated so multiple sprite renderer are created and it load same number texture multiple time.

So I want single number loaded single time only no repetition texture occur in graphical memory.

Because of this problem I am facing following problem that I already posted.

Android Device Screen Flicker

I want suggestions to overcome this problem from your side.


texts:
Similar to this question https://stackoverflow.com/questions/33904998/sfml-extremly-slow-irregular-framerate, I have created a small program to experiment with SFML
I have a very simple SFML test application on ubuntu 20.04 using SFML 2.5.1.
There are three circles. One under user control and one bouncing left to right.
Problems:

The one moving left to right is not very fast.
Even so the one under user control cannot keep up with it.
I am using a delta of 1 (pixel per frame?). If I increase this motion is jumpy rather than smooth.

Put simply it feels clunky.
So I am assuming I've made a noob error of some kind.
However, this seems to be the same basic SFML game loop commonly used.
How can I make this fast and slick feeling instead?
#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    const float FPS = 120.0f; //The desired FPS. (The number of updates each second).
    bool redraw = true;      //Do I redraw everything on the screen?
    window.setFramerateLimit(FPS);
    sf::CircleShape shape2(100.f);
    sf::CircleShape shape(10.f);
    sf::Clock clock;
    shape2.setFillColor(sf::Color::Green);
    shape.setFillColor(sf::Color::Red);

    sf::CircleShape alien(10.f);
    alien.setFillColor(sf::Color::Yellow);
    auto alienSpeed = 1.f;

    while (window.isOpen())
    {
        sf::Event event;
        float xDelta = 0;
        float yDelta = 0;
        bool moved = false;
        if (window.pollEvent(event))
        {
           if (event.type == sf::Event::Closed)
           {
              window.close();
           }
           if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            {
               xDelta -= 1.f;
               moved = true;
            }
            else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            {
               xDelta += 1.f;
               moved = true;
            }
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
            {
               yDelta -= 1.f;
               moved = true;
            }
            else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
            {
               yDelta += 1.f;
               moved = true;
            }
        }

        if (xDelta !=0 || yDelta != 0)
        {
           shape.move(xDelta,yDelta);
        }

        alien.move(alienSpeed, 0.f);
        if (alien.getPosition().x >= 190)
        {
           alienSpeed = -1.f;
        }
        else if (alien.getPosition().x <= 0)
        {
           alienSpeed = 1.f;
        }

        if(redraw)
        {
           window.clear();
           window.draw(shape2);
           window.draw(shape);
           window.draw(alien);
           window.display();
        }
    }

    return 0;
}

Note: cross posted to https://en.sfml-dev.org/forums/index.php?topic=27617.0


texts:
I am trying to highlight a rectangle of arbitrary height. I thought the easiest way to do this would be to create a separate "box" gameobject that outlines the rectangle.

I've tried with both a MeshRenderer + Transparent Texture, and a LineRenderer to outline the four points of the rectangle. Neither are very satisfactory.

(Line renderer on in the middle, scaled cube on the right)

What's the right way to go about this? I am trying to get something like the left rectangle - a simple perimeter of fixed width through four points of my choosing.


texts: Deferred Shading and Transparency Clarification?

texts:
So, this is a bit of a simple question, but I can't seem to find a real answer anywhere. I've been looking into implementing deferred rendering using MRT into my in-progress render engine, but I'm a bit hesitant to for the following reason.

I've read in a few places now that deferred shading does not support transparency natively, and if I wanted to achieve transparency, I would need to resort to forward shading of these transparent objects. But, the idea of "transparency" seems a bit vague because it seems as if there might (corrct me if I'm wrong) be two types of transparency.

One type being the sort of overlay transparency, where I, say, tile a wall with a brick texture. Then I want the wall to be 50% transparent so I apply that on top of the already textured object. This appears to be one "mode" transparency in which the engine, as part of its rendering pipeline, inserts this transparency manually.

The next type in my mind is using a texture that already has an alpha value associated with it, i.e. a 256x256 image of a person, where everything that isn't the person has an alpha value of zero. Then, if I were to billboard that image of the man onto a simple quad (which is what I'm actually trying to do in my game, for reference), would that sort of "native" transparency on the parts of the image with zero alpha still render as transparent, even in a deferred rendering situation?

Does such a distinction exist between these two types of transparency, or are they merely two sides of the same coin when it comes to deferred rendering?


texts:
I have a question about compute shaders.

My GPU is an AMD mobility Radeon 6490 which as the AMD website says supports OpenGL 4.1. However, when I check for my compatibility version via 'glGetString(GL_VERSION)' I get 4.3.12618 Compatibility Profile Context 13.250.18.0.
Does that mean I should be able to use compute shaders as they are introduced in OpenGL 4.3?

If I try to create a compute shader in my program GLenum type GL_COMPUTE_SHADER is unknown but I'm not sure if newest headers are included.

My GPU also supports the 'GL_ARB_compute_shader' extension.

So is there a special way to enable this extension or should I try to somehow include newer headers? Or will I not be able to use compute shaders at all (I don't want to use OpenCL)?

Thanks for answer.


texts: what is the best way to make a bunch of platforms appear randomly on a JFrame but close enough the player can reach them?

texts: Hi I'm trying to make a screen that will have a bunch of platforms that will place themselves randomly around a JFrame. I know how to do the stuff to make the character jump and to deal with the collisions just not a way to place the platforms on the screen randomly so they are close enough together that the character could reach. Any help is appreciated.


texts: How can I simulate physics on my curved LED strip?

texts:
I have a LED strip with 300 LEDs that I can control one by one:

https://github.com/cipold/pyledstrip

You can think of them as Adafruit NeoPixels:

https://www.adafruit.com/category/168

I have code to detect the physical positions of all LEDs using a camera and generate an x/y heightmap:

https://github.com/cipold/pyledstrip-detector

There is some experimental code to make use of the heightmap and let pixels race along the strip like on a rollercoaster:

https://github.com/Pixe1/pyledstrip-particles
Video: http://mnagel.net/oneshot/2018-03-02/particle.mp4/975a194be7cc6fc8/particle.mp4

The "physics engine" within that code is very ad-hoc, however. I want to rewrite it into something that more explicitly encodes the physical laws of classical/Newtonian mechanics.

I can easily simulate particles with mass, position, velocity (acceleration/gravity/forces). With multiple particles and gravity between them, I would end up with some kind of solar system. Or with constant overall gravity, one particle would fall down in a straight line, accelerating all the time.

What I really want is "global gravity" but restrict the particles to move along the path dictated by the LED strip/heightmap of waypoints (one degree of freedom along that path). How can I adequately model this restriction with formulas that are still reasonably physically accurate?


texts: How do we fill color between two raycast in unity?

texts:
I created a cube with meshfilter, boxcollider, rigidbody(in 2D platform) in unity. It creates a raycast towards each of the vertices in the scene(platforms, boxes and anything having box collider with it).
But, I am having a problem as how to fill a color between any two raycast I created.
My game scene:-

My script:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Lights : MonoBehaviour
{
    public GameObject[] sceneObjects;
    public float offset = 0.01f;
    RaycastHit hit, hit2;
    // Start is called before the first frame update

    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 myPos = this.transform.position;
        for (int i = 0 ; i< sceneObjects.Length; i++){
            Vector3[] mesh = sceneObjects[i].GetComponent <MeshFilter>().mesh.vertices;

            for (int j=0; j<mesh.Length; j++){
                    Vector3 vertiLoc = sceneObjects[i].transform.localToWorldMatrix.MultiplyPoint3x4 (mesh[j]);

                    Physics.Raycast (myPos, new Vector2 (myPos.x - vertiLoc.x - offset, myPos.y - vertiLoc.y - offset),out hit, 100);
                    Physics.Raycast (myPos, new Vector2 (myPos.x + vertiLoc.x + offset, myPos.y + vertiLoc.y + offset),out hit2, 100);
                    Debug.DrawLine (myPos, hit.point, Color.green);
                    Debug.DrawLine (myPos, hit2.point, Color.blue);
                    Debug.Log (vertiLoc);
            }

        }

    }

}


texts:
I need to determine the user's play area size, however it seems as though the only way to achieve this is by using the following code from this forum post:
List<XRInputSubsystem> inputSubsystems = new List<XRInputSubsystem>();
SubsystemManager.GetInstances<XRInputSubsystem>(inputSubsystems);
if(inputSubsystems.Count > 0)
{
    List<Vector3> boundary = new List<Vector3>();
    if(inputSubsystems[0].TryGetBoundaryPoints(boundary))
    {
        // boundary is now filled with the current sequence of boundary points
    }
}

This however only works when using the new XR Plugin Management system, however there is currently no support for the HTC Vive?
Is there another way to achieve this?
Thanks in advance for your help!


texts: Why does my line disappear against a white image?

texts:
A GIF is worth a 10002 words:

Why does the rainbow-colored line disappear when it is displayed against the white image?

A few more details: The line is a Vectrosity line that is rendered using Unity's built-in Unlit/Transparent shader.  The white square in the background is a RawImage that displays a pure white PNG texture.  The line is closer to the camera in the scene, but it is disappearing when it is rendered on top of the white RawImage behind it.

If I change my line's material to use the Unlit/Color shader, the line shows up as expected:

I'm using Unity 5.6.1f1.


texts: Identifying connected lines drawn free-hand by a user

texts:
I have a series of 'images' described by a mixture of connected lines and curves. Users will draw on the screen, free hand, and my goal is to break their drawing down into a series of lines and curves that can be matched with the 'images' in my set.

For the sake of simplicity, let's assume this is occurring on a touch screen. These lines will be connected. Each time the user's finger moves, the dx and dy is recorded. The drawing is considered complete and analyzed when the user's finger leaves the screen.

I'm having trouble figuring out a good way to break the user's drawing down into lines. Is there any well known approach to this problem, a C++ library that solves it, or any good articles/technical papers on how to achieve this?


texts: Implementing time slowdown in a multiplayer game

texts:
My game has first-person melee combat that is based on directional attacks that are controlled with mouse gestures.  For example, a downward slash is most effectively blocked by a shield held up high.  I'd like to add a short "focus" mode while the player is holding down the mouse button to use their weapon/shield.  It should last no more than a second or so.

The problem is how to make this work when there are other players in the vicinity.  Nearby players shouldn't be slowed down or notice that the other player has slowed down time - it should look completely normal to them.  The players also need to be synchronized in "game time".  How can I do this?


texts: Moving ships between two planets along a bezier, missing some equations for acceleration

texts:
OK, I already posted this over at math.stackechange.com but didn't get any answers :(

First of here's a picture of my problem, the description follows afterwards:

So I got all the points and values set up.

The ship starts out moving around the left planet P1 with S=0.27 Degrees per gametick, when it reaches Point A it starts following the bezier curve till it reaches Point D, then it travels around the right planet P2 with S=0.42 Degrees per game tick. The difference in S is so that the travel with the same movement speed around the planets.

So far so good, I got that up and running, now my problem.

When S P1 and S P2 differ to much, the ship jumps between the two speeds when it reaches it's destination, which looks pretty bad. So I need to accelerate the ship between Point A and Point D from S P1 to S P2.

The thing I'm missing are in purple, those are:

A way to calculate the ticks it takes the ship to move along the bezier considering the acceleration.
And a way to find a position on the bezier curve based on T, again considering the acceleration.

ATM I calculate the length of the bezier by calculating the distance between N of its points. So what I think I need, is a way to scale the T I need to put into my bezier calculation accordingly to the acceleration.


texts: How to propertly send map to clients in MMO?

texts:
I'm designing a game where the map has 1 M tiles. The game is simple, is a 2D game with low graphic requirements and without player movements, only change states, so I don't need to update player positions for example. But I have a doubt about how to synchronize the map.

When a client connects, the server should send him data related with proximity tiles. Each tile is represented with a different picture, so I can represent them with an id (integer). Developing in c#, each tile requires 4 bytes to store the id. So when the client connects, I have to send him (4 bytes*number of tiles). Sending data of 1000 tiles (a 30x30 grid), I'm sending 4 kb, and this is just in the first connection. When the client player moves, I have to send him more and more data, which has not a good performance.

On the other hand, if I store all the ids in the client, I will need to store 1M*4 byte = 4 mb per client. This is just to store tile ids, but it seems to be ok.

How can I design or optimize the data messaging ?


texts:
I'm trying to render an Inter Quake Model(http://lee.fov120.com/iqm/) in DirectX9 that I exported from blender.

I want to display animations which IQM supports and my model format does not.

The model is a cylinder.

It loads fine in the iqm sdk opengl viewer but when i try to render it in directx9 using for example(this is just to render the vertices):

IDirect3DDevice9 * device;
HRESULT hr = S_OK;

for(int i = 0; i < nummeshes; i++)
{
    iqmmesh &m = meshes[0];

    hr = device->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0,
    3*m.num_triangles, m.num_triangles ,&tris[m.first_triangle] ,D3DFMT_INDEX32
    ,inposition ,sizeof(unsigned int));
}

It renders like this:

Incorrect

The light grey bit that looks like two triangles in the middle is what is rendered(ignore the other stuff).

Whereas it is meant to look like this(using a custom importer which I designed which matches what is displayed in blender):

Correct

Anyone have any suggestions on what might be going wrong?


texts: Why the mouse doesn't move in mouse-look feature of RPG/FPS games?

texts:
Description
The mouse look (or free look, i.e., move the mouse to change the view/camera) is common in RPG and FPS games. In my cloud game project, I tried to achieve this feature. Before programming, I tested an RPG game (Genshin) in Windows, I started it directly in my PC and used spy++ to check what happened when I moved the mouse. I got these results:

It seemed that however I moved the mouse, although the role's view changed, the positions in WM_MOUSEMOVE messages didn't change too much. Actually, 640 and 343 were about the half of the resolution sizes (1280*720).
Question
How those games achieve this: move the mouse and change the role's view, but the positions in messages don't change? What bottom winapis are used?
(I hooked ClipCursor and the input parameters of ClipCursor were just my screen's width and height.) In cloud games, I need to use remote mice (clients' inputs) to achieve this feature, what can I do?