texts: Is it possible to completely avoid copying image data when uploading textures to the GPU on iOS?

texts:
I am not a game developer, but I have been doing iOS software engineering for many years. I have a particular interest in graphics and animation, but the finer details are still a little foreign to me.

Here is the scenario I am working with:

I have an extremely memory-contrained iOS environment (i.e., no more than 16-20MB of active memory usage) where I am trying to display many high-resolution sprite frames in rapid succession to show an animation. Each frame might be up to 1210x1210 pixels, and I can have up to 200 frames in a single animation.

Obviously, these constraints mean I have to completely optimize my memory usage. There's no way I can even consider having more than one frame of an animation inflated and being used by my application's memory at any given point. Yet I need images to be loaded super fast.

I had considered trying to pack a bunch of frames together into a PVRTC2 or PVRTC4 image file. The quality and disk-space usage of PVRTC files is superior to other formats, considering they're only using 2 or 4bpp.

I attempted to use SpriteKit to read the texture atlas I created and display the image frames. This "worked" in that it did what I wanted, but the memory usage was insane, around 600-700MB. Apparently, SpriteKit is always going to make copies of texture data for its own use, which is unfortunate.

My question is if it's possible to completely bypass copying image data by my application before sending it to the GPU for rendering. My understanding was that the whole point of PVR image formats was to be an exact representation on disk of the uncompressed image data that the GPU can use directly, without the need for copying the image into its own format. (As far as I know, PVR is the format the GPU needs to render the texture.)

Indirectly, I was able to mostly achieve what I wanted using a framework I helped develop for iOS called Fast Image Cache. Basically, it creates image tables on disk that are fully uncompressed and are page-aligned in advance such that Core Animation can use the image data directly without doing a single memcpy. Fast Image Cache uses mapped memory to further avoid any copies whatsoever. In essence, data goes directly from disk to being rendered on display without any copies being made. (At least, no copies that are made within the context of your application, which could be held against your memory usage limits.)

The problem with FIC is that it is a very naive image table. It doesn't do any sort of texture packing. For my testing, I loaded each frame of the animation as a separate image inside FIC. There was a ton of disk IO overhead going on. In addition, FIC only supports 32bpp (with or without alpha) and 16bpp bitmap formats, which means the image tables are huge.

Is there a way for me to achieve something similar to FIC using OpenGL and PVRTC images? If I need to build out my own simple texture atlas support to map regions of PVRTC images to individual animation frames, I'll do that, though it'd be nice if something else besides SpriteKit could do this for me.

The crucial point is being able to quickly load fairly large image data to be rendered without impacting my app's memory footprint.


texts: How do I get access to the SpriteBatch service in my Sprite class using XNA?

texts:
I have the following Sprite class (leaving out everything that doesn't pertain to my question):

public class Sprite
{
    public Texture2D Texture { get; set; }
    public Vector2 Position { get; set; }
    private SpriteBatch _spriteBatch;

    public Sprite(Texture2D texture, Vector2 position)
    {
        Texture = texture;
        Position = position;

        // what code do I put here?
        _spriteBatch = ???
    }

    public virtual void Draw()
    {
        _spriteBatch.Draw(Texture, Position, Color.White);
    }

In my Game1.cs class, I register the SpriteBatch as a service:

protected override void LoadContent()
{
    _spriteBatch = new SpriteBatch(GraphicsDevice);
    Services.AddService(_spriteBatch);
}

Problem is, I don't know what code to put in the Sprite constructor to get the SpriteBatch object from the service. It doesn't have access to the Game.Services object. How would I load the service in this case?


texts: Unable to instantiate objects Straight in unity

texts:
I am  creating a match card game in unity and I want to place cards in straight direction that is one below another and so on... But with my formula It's showing cards one after another.Please tell me whats wrong with my code.
Following is my code -

    void SpawnCards(){
    int cardsinrow = 4;
    int cardsincolumn = cardslist.Count/cardsinrow;
    if(cardslist.Count % cardsinrow > 0)
        cardsincolumn += 1;
    float spacebetweencards = .2f;

    for(int i=0; i<cardslist.Count; i++){
        GameObject mc = Instantiate(memorycard, new Vector3((i%cardsinrow+(i%cardsinrow*spacebetweencards))-(cardsinrow/2f)+spacebetweencards, 0, (i/cardsinrow+(i/cardsinrow*spacebetweencards))-(cardsincolumn/2f)+spacebetweencards), memorycard.transform.rotation) as GameObject;
        mc.GetComponentInChildren<MemoryCard>().SetMemorycard(cardslist[i].texture, cardslist[i].number);
    }
}


texts: Android game programming seperate game logic thread from drawing thread

texts: Ok so I want to know what is a proper way to create a multi threaded game. What I have tried is implement a wait and notify between the game logic thread and the drawing thread, but I believe this is a very bad way to do it because one thread waits for the other to finish what it is doing before it can continue to do it`s own task. I mean, I think this kind of beats the whole point. So a better way I am thinking of would be to have blocking queues(I would need more than one for all the different types of data in my game) and the updating thread would put all of the updated/processed values into it and if it was full, the updating thread would block. The drawing thread would then read all of those values and if the queues were empty it would block. This way both the threads are fully utilized. But I don't know if this would be the professional or good way to do it, which is why I am posting this so I can get a little guidance. Thanks!


texts: Can I develop a game using C++ and deploy to XBOX 360?

texts:
I'm a C# developer and an enthusiast of XNA, but I'm really disappointed with the game engines available for XNA.

I was using Torque X, which is really good, but GarageGames no longer supports Torque X for XNA 4.1. I searched for other engines, but only the sunburn was worth it and would have to pay - I already spent money with Torque.

Based on this, I'm thinking about starting to develop in C++. Can I develop with some C++ engines and deploy to XBox 360?


texts: How to convert OpenGL 2.0 code to OpenGL-ES 2.0?

texts:
I have a 3D game library that uses OpenGL 2.0 for PC and I need to convert it to OpenGL-ES 2.0 to compile it for Android.
Because the library is huge, I'd like to avoid converting it line-by-line by hand.
Is there some faster way I can convert desktop OpenGL to OpenGL-ES source code, like a wrapper, or maybe some layer running on Android that converts desktop OpenGL to ES at runtime?


texts:
I've read a lot about transformations: model to world space, world to camera space and projection transformationsl but when programming it, I can't get things right. I think I'm missing something, so here is my example code:

package com.test.rendering;

import...

public class Test extends ApplicationAdapter {
Texture texture;
Matrix4 projection;
Matrix4 transform;
SpriteBatch batch;
float angle = 0f;

@Override
public void create () {
    float width = Gdx.graphics.getWidth();
    float height = Gdx.graphics.getHeight();

    projection = new Matrix4();
    projection.setToProjection(
            -width / 2,
            width / 2,
            -height / 2,
            height / 2,
            1,
            100);

    batch = new SpriteBatch();
    batch.setTransformMatrix(transform);
    batch.setProjectionMatrix(projection);

    texture = new Texture("badlogic.jpg");
    Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}

@Override
public void render () {
    Gdx.gl.glClear(Gdx.gl.GL_COLOR_BUFFER_BIT);

    angle = (angle + 0.5f * Gdx.graphics.getDeltaTime()) % 360;

    transform = new Matrix4();
    //translate the world so we can see the texture at z = 0
    transform.translate(0.0f, 0.0f, -5.0f);
    transform.rotate(Vector3.X, angle);

    batch.setTransformMatrix(transform);

    batch.begin();
    batch.draw(texture, -texture.getWidth() / 2, -texture.getHeight() / 2);
    batch.end();
}

@Override
public void dispose () {
}
}

If you run this code you will see a very weird transformation: the texture starts rotating, but then stretches until some part of the screen, and then slowly disappears. I was expecting to see the texture just rotating around the x axi, with no stretching. Why is this happening? What is wrong with my code?


texts: How can I detect handedness of normal maps in a shader?

texts:
I've implemented normal maps into my game renderer using the formulas by Christian Schuler.

It works OK with most normal maps but some not so much since in some the Y component (green) is reversed. Apparently there is no real standard here and Maya does it one way and Max does it the other way.

I'd like to be able to look at a normal map's values and somehow determine which scheme is being used, if that's possible.

Also, though I have not actually seen any, some normal maps appear to use only two channels and the third channel is left blank and calculated at runtime. Ideally I would be able to detect those, too. I figure maybe the Z channel is all zeros? I am not sure that would save any space though so maybe it is some other scheme.

Seems like an obvious desire, but I don't see any references to this. but then, maybe it's not really possible.


texts: How are the graphical effects in the Android game Orbital created?

texts:
I would be very grateful if someone could tell me how the graphics (and in particular, the lighting effects) for this game, Orbital, are created. Would it be OpenGL?

For some background: I'm new to this, and I really like these style of graphics, but I've no idea where to begin -- I'm just trying to figure out which direction I should be headed in. I have a very basic knowledge of Java, and I'm just starting to work with Android now. I have made simple games in Java in the past.


texts:
I am trying to use double buffering in pygame. What I'm trying to do is display a red then green screen, and switch from one to the other. Unfortunately, all I have is a black screen. I looked through many sites, but have been unable to find a solution. Any help would be appreciated.

import pygame, sys
from pygame.locals import *

RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
bob = 1

pygame.init()
#DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
DISPLAYSURF = pygame.display.set_mode((1920, 1080), pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.FULLSCREEN)
glClear(GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
running = True
while running:

if bob==1:
    #pygame.draw.rect(DISPLAYSURF, RED, (0, 0, 1920, 1080))
    #pygame.display.flip()
    glBegin(GL_QUADS)
    glColor3f(1.0, 0.0, 0.0)
    glVertex2f(-1.0, 1.0)
    glVertex2f(-1.0, -1.0)
    glVertex2f(1.0, -1.0)
    glVertex2f(1.0, 1.0)
    glEnd()
    pygame.display.flip()
    bob = 0

else:
    #pygame.draw.rect(DISPLAYSURF, GREEN, (0, 0, 1920, 1080))
    #pygame.display.flip()
    glBegin(GL_QUADS)
    glColor3f(0.0, 1.0, 0.0)
    glVertex2f(-1.0, 1.0)
    glVertex2f(-1.0, -1.0)
    glVertex2f(1.0, -1.0)
    glVertex2f(1.0, 1.0)
    glEnd()
    pygame.display.flip()
    bob = 1

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    elif event.type == KEYDOWN:
        if event.key == K_ESCAPE:
            running = False

pygame.quit()
sys.exit()

I'm using Python 2.7 and my code need to be os independent.

Thanks for your help.


texts: Is there a way to prevent the user from playing the game simultaneously on 2 devices

texts:
Our game uses Google Play Services for authentication, multiplayer and cloud saves. We save the users inventory as a cloud save, and as the player partakes in multiplayer matches they might use items out of their inventory (coins, etc). Also, they may use in app purchases to add items to their inventory.

I want to try and avoid the hassle of cloud save game conflicts when the player (for whatever reason) decides to play the game on 2 devices at the same time.

I worry they may lose data when resolving save games and as their save games may contain coins and other items obtained via IAPs, this is unacceptable.

Is there a way to check if the user is currently logged in to the game on anther device and is actively playing on that device? We don't have our own servers and use GPS for all our work. What is a possible solution here?


texts: Unreal Crashing just by me adding components

texts:
I have created an actor cpp class called gun base.  for some reason it is causing a perpetual crash in unreal.
this is its header file.
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "GunBase.generated.h"

UCLASS()
class GIZMOSHOOTER_API AGunBase : public AActor
{
    GENERATED_BODY()

public:
    // Sets default values for this actor's properties
    AGunBase();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:
    // Called every frame
    virtual void Tick(float DeltaTime) override;
    //virtual void PullTrigger();

private:

    UPROPERTY(EditDefaultsOnly)
    USoundBase* FireSound;
    UPROPERTY(EditDefaultsOnly)
    UParticleSystem* MuzzleFlash;

    UPROPERTY(EditDefaultsOnly)
    USceneComponent* RootSceneComponent = nullptr;
    UPROPERTY(EditDefaultsOnly)
    UStaticMeshComponent* GunMesh = nullptr;
    UPROPERTY(EditDefaultsOnly)
    USceneComponent* BulletSpawnPoint = nullptr;
};

and this is the cpp file.
// Fill out your copyright notice in the Description page of Project Settings.

#include "GunBase.h"
#include <Components/StaticMeshComponent.h>
#include <Components/SceneComponent.h>

// Sets default values
AGunBase::AGunBase()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;
    RootSceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
    RootSceneComponent->SetupAttachment(RootComponent);
    GunMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    GunMesh->SetupAttachment(RootSceneComponent);
    BulletSpawnPoint->SetupAttachment(GunMesh);  //This is the line its complaining about
}

// Called when the game starts or when spawned
void AGunBase::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void AGunBase::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}

The crash is saying something about an exception access violation, and in particular is referencing line seventeen  on the cpp file which has a comment on it.  Just in case this means something, I have tried several things to get this code to work, I then builded it, and tried to open the project in unreal again but i always got a crash.  thanks.
Edit:  I had a function in the header file (pulltrigger its commented out) that was causing me errors but I commented it out and the crash is still occuring.


texts: How can I blend grass decals in a transparent alpha channel in 3D? LibGDX

texts:
I'm new to 3D and trying to create grass simulation using decals in libGDX.

I'm following the logic outlined here.

Atm my grass decal is a billboard of grass stems with a transparent background. I've placed 3 decals together in the form of a triangle.

When I pan the camera around at times the decals blend together but most of the time you can see the outline of the decal and you can distinguish between the pngs.

Can someone please help me understand a way to blend my decals better?

The decal:
http://www.reinerstilesets.de/3dtextures/billboardgrass0002.png

The code:

public class Grass implements Screen {
    private FirstPersonCameraController camera_control;
    private PerspectiveCamera camera;

    private Mesh floor_mesh;
    private Vector<Texture> grass;

    private Vector<Decal> decals;
    private DecalBatch decalBatch;
    private Vector<TextureRegion> grass_regions;

    private ShaderProgram shaderProgram;
    private Stage stage;

    @Override
    public void show() {
        stage = new Stage();
        decals = new Vector<Decal>();
        grass = new Vector<Texture>();
        grass_regions = new Vector<TextureRegion>();

        //camera
        camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.near = 0.01f;
        camera.far = 10f;
        camera.position.set(1, 2, 5);
        camera.update();
        camera_control = new FirstPersonCameraController(camera);
        camera_control.setVelocity(3);
        camera_control.setDegreesPerPixel(.25f);
        Gdx.input.setInputProcessor(camera_control);

        //grass
        grass.add(new Texture("billboardgrass0002.png"));

        for(Texture t : grass){
            grass_regions.add(new TextureRegion(t));
        }

        decalBatch = new DecalBatch(new CameraGroupStrategy(camera));
        for(int i = 0; i < 3; i++){
            decals.add(Decal.newDecal(0.75f, 1.25f, grass_regions.get(0), true));
        }

        //set grass
        decals.get(0).setPosition(1f, 0, 1f);
        decals.get(1).setPosition(1.1f, 0, 1.1f);
        decals.get(1).setRotationY(45);
        decals.get(2).setPosition(.8f, 0, 1.1f);
        decals.get(2).setRotationY(-45);
    }

    @Override
    public void render(float delta) {
        //gl
        Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        //Gdx.gl20.glClearColor(1, 1, 1, 1);
        Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
        Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);
        Gdx.gl20.glEnable(GL20.GL_TEXTURE_2D);
        Gdx.gl20.glEnable(GL20.GL_BLEND);
        Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl20.glCullFace(GL20.GL_NONE);

        //camera
        camera_control.update();

        //disable depth writing
        Gdx.gl20.glDepthMask(false);

        //draw grass decals
        for(Decal d : decals){
            decalBatch.add(d);
        }
        decalBatch.flush();

        //stage
        stage.getViewport().update(1280, 720, true);
        stage.act(delta);
        stage.draw();
    }

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

    @Override
    public void hide() {}

    @Override
    public void pause() {}

    @Override
    public void resume() {}

    @Override
    public void dispose() {
        shaderProgram.dispose();
        decalBatch.dispose();
        decals.clear();

        for(Texture t : grass){
            t.dispose();
        }

        grass.clear();
        floor_mesh.dispose();
    }
}

Edit:
disabled depth buffer writing before drawing decals,
now looks better:


texts: How can I prevent resizing of an Ogre3D object once imported into jMonkeyEngine?

texts:
I created an object in Blender:

Then I exported it as a mesh.xml file and attached it to the game scene:
[Note: The gray color is the ground.]

In the game I end up with have a smaller, horizontal tower. Any suggestions?

Note: I exported the file with "Force Camera", "Force Lamps" and "Export Scene" unchecked and "Swap Axis: x,y,z".


texts:
I need to get local coords from global coords. I did not find ready-made examples.

Please help me how to do it on the example image. Thank you!

UPDATED:

Here's the method in the java, created thanks to your help! It works for me :) Thank you!

public static double[] getLocalFromGlobal(int pointX, int pointY, int localX, int localY, float angle) {
    float px = pointX - localX;
    float py = pointY - localY;

    double cos = Math.cos((Math.PI / 180) * angle);
    double sin = Math.sin((Math.PI / 180) * angle);

    double finalX = (px * cos) + (py * sin);
    double finalY = -(px * sin) + (py * cos);
    return new double[]{finalX, finalY};
}


texts: libgdx calculate vector to find new points

texts:
I am working with vector2 in libgdx.
I have (x1,y1) and magnitude 'M' with an angle 'D'.
How could I calculate (x2,y2) using vector2.

Thank You


texts: Support multiple gamepad layouts (Unity 2017.3)

texts:
My game supports touchscreen, keyboard + mouse and the Xbox One controller and the input so far works properly. Now I also want to add a second layout for the gamepad the player can then pick in the settings, e.g.:

Layout 1: Fly up with "A", fly down with "B" (so two buttons)

Layout 2: Fly up with "LB", fly down with "LT" (LT uses an axis, not a button!)

With keyboard/touchscreen and gamepad input I was able to create two different inputs in Unity's InputManager for the same thing and they would then trigger depending on which input device you're using.

I thought about adding a bool for the layouts and checking it every time a button is pressed but that sounds more like a quick and dirty solution. Descriptions of InputManagers I've found so far make it sound like they're used for rebinding keys or to support different gamepads (e.g. Xbox One and PS4), which I don't want/need (plus, these InputManagers are usually pretty expensive).

How do you handle actual different layouts that use the same buttons/axis for different things, especially with something using a button in the first layout and an axis in the second?


texts: How do I calculate the position of a vehicle moving between tiles, over time?

texts:
I'm working on a small multiplayer game where players can create cities, and these cities will be placed on what's called the "world map." The world map is basically a giant coordinate plane made up of tiles, and the server will load the "world map" in chunks from the database relative to a player's position on the world map.

Now, I want players to be able to send planes from their city to another spot/tile anywhere on the world map. Say for instance player who owns City 1 at position 10,10, wants to create an oil_well at position 70,30. I want a plane to fly from the departure point to arrival point, and client that loads the chunk will see that plane flying across the map.

How can I make the server calculate where the plane is? I have the following information:

departure_time, origin_x, origin_y, arrival_x, arrival_y, speed. speed is the time in seconds that a plane can cross a tile on the world map.

I also have distance, which is simply calculated as (distance formula):

var distance = Math.sqrt(Math.pow( data.arrival_x - data.origin_x , 2) + Math.pow( data.arrival_y - data.origin_y , 2));

Again, how can I calculate the current position of a moving plane on this world map? Because the plane can fly at many different angles, depending on the angle of departure point → arrival point.


texts: If a 3D vector represents a point, how can it have a length?

texts:
I am trying to understand vector arithmetic (and specifically its use in the Unity engine). I am not able to figure out how a vector can have a length (magnitude) even though it only represents a point (position and direction)?

Does that mean that the magnitude is simply its distance from the origin point (0, 0, 0)? Or am I missing something?


texts: Navigate multiple Units on a grid through a tight space with different directions

texts:
I just started learning about pathfinding algorithms.
Assume we have this scenario:

Blue and Green can move only on those tiles. They can also talk to each other.
Blue wants to go through the tunnel and green wants to go too, however both need to pass each other somehow. In case of a "basic" A* pathfinding algorithm they will both get stuck in the tunnel.

To prevent this issue i had some Ideas:
- Blue can tell green that he should move back first (give blue priority) when they both step next to each other (problems arise when there are more than 2)
- A better algorithm, that calculates this like an automatic traffic regulator (one will wait till the other frees the path) --> seems complicated

Now I am wondering if there are more efficient methods, how its done in general, if you have better ideas, if you can point me to some algorithms or some papers that adress this issue.


texts: Is there an efficient, available online, algorithm for converting a matrix of squares into a triangle strip?

texts:
Imagine having a 4x4 square, with 16 smaller squares inside of it, with associated data on what the squares should look like (ie., opacity, colour, etc...).

Is there an existing, efficient, algorithm, for converting this set of squares into an open-gl compatible triangle strip?


texts: How do I get my sprite to do a regular jump instead of jolt up?

texts:
I have been getting into game development and I have made some progress. I have come across an obstacle which is jumping I managed to get the Jumping to semi work but it doesn't look like a jump but instead it Jolts up or teleports up.
This is how it looks:
It's a bit slower thanks to the gif but as you can see it just jolts up. I tried implementing multiple ways to jump and I tried to stay with the velocity and acceleration method.
This is what I have right now:
sf::Vector2f velocity = sf::Vector2f(0,0);
float accelaration = 1.f;
void Player::updatePhysics(int deltaTime) {
    if (playerCount == 1) {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            velocity.x -= accelaration * deltaTime;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            velocity.x += accelaration * deltaTime;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W) && !isJump) {
            isJump = true;
            jumpDownEnd = false;
            velocity.y -= 30 * deltaTime;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S) & velocity.y > 800) {
            velocity.y += accelaration * deltaTime;
        }
    }

    if (velocity.y > 800) {
        velocity.y = 800 - player.getGlobalBounds().height / 2;
    }
    else {
        velocity.y += gravity ;
    }
    player.setPosition(velocity.x, velocity.y);
}

Notes

I have tried a couple of other things like storing player position and adding velocity and multiplying by deltaTime and it worked but I got rid of it because I got a few bugs.
Also I tried to change the velocity.y -= 30* deltaTime to velocity.y = 30* deltaTime and all it did was reduce height by a bit.
Also the reason I am not multiplying velocity by delta time when setting position is because it starts to twitch when it gets further away from the original position.
I have tried searching for answers but they didn't help me find any solutions.
Also deltaTime is as milliseconds instead of seconds. I constantly get a deltaTime of 15 or 16 if that helps.
Update

I have made the code to add velocity to player position but now the jump is just super fast and still jolts up.
void Player::updatePhysics(int deltaTime) {
    velocity.x = 0;
    if (playerCount == 1) {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            velocity.x -= accelaration;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            velocity.x += accelaration;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W) && !isJump) {
            isJump = true;
            jumpDownEnd = false;
            velocity.y = -300;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S) & velocity.y > 800) {
            velocity.y += accelaration;
        }
    }
    velocity.y += gravity * deltaTime;

    playerPos.x += velocity.x * deltaTime;
    playerPos.y += velocity.y * deltaTime;

    if (playerPos.y > 800) {
        playerPos.y = 800 - player.getGlobalBounds().height / 2;
        velocity.y = 0;
    }

    player.setPosition(playerPos);
}


texts: drawing a horizon / sky in OpenGL ES 2.0

texts:
I want to render a sky: My camera is at the origin, and I want there to be a white background for all world coordinates with z < 0 (would normally be considered y > 0, but I have a different coordinate system via glLookAt()).

I thought I may be able to do this in the fragment shader by multiplying the inverse MVP matrix with the corresponding clip space (?) coordinate (I compute that matrix on the CPU each frame by calling Matrix.invertM()). To get my vertices into the fragment shader, I use a varying variable (I wasn't sure if I could access gl_Position in the fragment shader) and passed the position right through; not sure if my syntax is right (see below):

Vertex Shader:

attribute vec4 position;
varying vec4 vp;
void main() {
  gl_Position = position;
  vp = position;
}

Fragment Shader:

precision mediump float;
uniform mat4 inverseMatrix;
varying vec4 vp;
void main() {
  vec4 inversePosition = inverseMatrix * vp;
  if (inversePosition.z > 0.0) {
    gl_FragColor = vec4(0,0,0,1);
  } else {
    gl_FragColor = vec4(1,1,1,1);
  }
}

Question:

Does this approach seem sane? Should I use some other approach that doesn't involve multiplying each fragment coordinate with the inverse MVP matrix?


texts: How to retrive the original position of an axis to Vector3?

texts:
float x = Random.Range(-1f , 1f) * magnitude;
        float y = Random.Range(-1f , 1f) * magnitude;

        transform.localPosition = new Vector3(x, y, originalPos.z);

Here I'm trying to retrive the original position of z(without any changes) to the vector3. But in visual studio 2017 is showing an error like this

How to resolve this?


texts: I'm new to game development and XNA. I have this depthmap image and I want to render it in 3D, how do I do it, any tutorial or blog post would be helpful.


texts: Curiosity on any Smartphones that Run on Android 2.3.3 with Different Screen Reoslution

texts:
I have a question regarding about any smartphones that run only in Android 2.3.3. Is the size of screen or the screen resolution is always HVGA or does it have capable of running this OS (Android 2.3.3) on big screen size (4" to 5") at about 720x1280?

I'm thinking of the game's compatibility depending on the version of the Android OS and the screen resolution, which affects the change of coordinates especially for assigning touch buttons and drag-n-drop at exact location, before I'm gonna decide to make one. My program works on the Android 4 ICS and Jellybean, however, will that work on Android 2.3.3 in spite of precise touch coordinate or just dependent on the screen resolution (regardless how large it is) as the X and Y coordinate?

And take note, I'm using Eclipse IDE for Java developers.


texts:
I am currently working on some FX trail effect. Here's the situation, you have a fast moving object that puts trail on another object.

Here's how it works for the moment. I have some kind of stamp texture (the object) that is printed onto another texture of the receiver object. When the object is moving not to fast, you can see the trail effect.
But the problem appears when the object is moving to fast, then you don't see the trail but only the stamp texture printed at some points.

The issue is quite logical and linked to the time when the update function is called (I am using Unity). The function is not called enough so it's missing some positions and thus the trail effect


texts:
Well, I'm a beginner in libGDX and till now I used image-buttons to draw something which can be clicked for example. However image-buttons are really hard to draw, in fact you have to use it with a stage and a viewport, instead textures are easier. I noticed that textures are ALWAYS at the same position in our game if we change device and this is very useful, instead image buttons can give you lots of problems because you have a stage and a viewport, above all if there are textures too. So I decided to bypass the image buttons and I did something like this:

public class MyView extends Texture implements InputProcessor
{

   public Tasto(String string)
   {
       super(string);
       Gdx.input.setInputProcessor(this);
   }

   //all InputProcessor methods
}

In this way I have a texture which is clickable and I'll continue in this way if there aren't problems. But so image buttons are useless. So, what are image buttons used for? Why using them if I can do in this way?


texts: Add picture in the Hierarchy view in Unity

texts:
How can I add a picture in the Hierarchy view in Unity? For example, Dragon bones does it automatically. Here it is :

As you can see there is a picture on the right of the gameObject name.


texts: Object automatic create new with old every time when load / save game.?

texts:
My problem with this DontDestroyOnLoad(cube.gameObject); When I load my player position its create new object with default and saved position respectively. I have a screen shot for better understand.

First scene without save

Second scene with save game.

Here is my code.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine.SceneManagement;
using System.Collections.Generic;

public class Player : MonoBehaviour {

public static float speed;
//public static Player control;
public float moveSpeed = 10f;
public float turnSpeed = 50f;
public Transform cube;
public float x, y, z,x1 ,y1, z1;
public int s;

//public static List<Game> savedGames = new List<Game>();
public static Player Instance;
// Use this for initialization

// Update is called once per frame

void OnTriggerEnter(Collider other) {

    if(other.tag == "Player1"){
        DontDestroyOnLoad(cube.gameObject);
        //DontDestroyOnLoad (other.gameObject);
    }
}

void Awake ()
{

    if (Instance == null) {
        DontDestroyOnLoad (this.gameObject);

    } else {
        DestroyObject(gameObject);
    }
}

public void Start () {
    speed = 50f;
}

//Update is called once per frame
public void Update () {

    if(Input.GetKey(KeyCode.W))
        transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);

    if(Input.GetKey(KeyCode.S))
        transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);

    if(Input.GetKey(KeyCode.A))
        transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);

    if(Input.GetKey(KeyCode.D))
        transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);

    }

public  void Save(){

    //Player.savedGames.Add ();
    BinaryFormatter bf = new BinaryFormatter ();
    FileStream fs = File.Create ("D:/playerinfo3.txt");

    playerData pd = new playerData ();
    PlayerPrefs.SetInt ("currentscenesave",SceneManager.GetActiveScene().buildIndex);

    PlayerPrefs.SetFloat ("cubeposx",cube.position.x);
    PlayerPrefs.SetFloat ("cubeposy",cube.position.y);
    PlayerPrefs.SetFloat ("cubeposz",cube.position.z);
    PlayerPrefs.SetFloat ("cuberotx",cube.eulerAngles.x);
    PlayerPrefs.SetFloat ("cuberoty",cube.eulerAngles.y);
    PlayerPrefs.SetFloat ("cuberotz",cube.eulerAngles.z);

    pd.x = PlayerPrefs.GetFloat ("cubeposx");
    pd.y = PlayerPrefs.GetFloat ("cubeposy");
    pd.z = PlayerPrefs.GetFloat ("cubeposz");
    pd.x1 = PlayerPrefs.GetFloat ("cuberotx");
    pd.y1 = PlayerPrefs.GetFloat ("cuberoty");
    pd.z1 = PlayerPrefs.GetFloat ("cuberotz");
    pd.s = PlayerPrefs.GetInt ("currentscenesave");

    SceneManager.LoadScene (pd.s);
    bf.Serialize (fs,pd);
    fs.Close ();

}

  public void Load(){
    //transform.position = new Vector3 (PlayerPrefs.GetFloat ("cubeposx"), PlayerPrefs.GetFloat ("cubeposy"), PlayerPrefs.GetFloat ("cubeposz"));
    if(File.Exists("D:/playerinfo3.txt"))
    {

        BinaryFormatter bf = new BinaryFormatter ();
        FileStream fs = File.Open ("D:/playerinfo3.txt",FileMode.Open);
        playerData pd = (playerData)bf.Deserialize (fs);
        pd.x  = PlayerPrefs.GetFloat ("cubeposx");
        pd.y = PlayerPrefs.GetFloat ("cubeposy");
        pd.z = PlayerPrefs.GetFloat ("cubeposz");
        pd.x1 = PlayerPrefs.GetFloat ("cuberotx");
        pd.y1 = PlayerPrefs.GetFloat ("cuberoty");
        pd.z1 = PlayerPrefs.GetFloat ("cuberotz");
        fs.Close ();
        SceneManager.LoadScene (PlayerPrefs.GetInt ("currentscenesave"));
        cube.position = new Vector3 (pd.x,pd.y,pd.z);
        cube.rotation = Quaternion.Euler (pd.x1,pd.y1,pd.z1);

        Debug.Log ("currentscenesave"+ " "+ pd.s);
        Debug.Log ("currentscenesave"+ " "+ pd.x);
        Debug.Log ("currentscenesave"+ " "+ pd.y);
        Debug.Log ("currentscenesave"+ " "+ pd.z);
    }

  }

  [Serializable]
  class playerData{

    public float x, y, z;
    public float x1, y1, z1;
    public int s;

 }

}


texts: How do I find two points at an angle on opposite sides of a circle?

texts:
With reference to my previous question:

I'm using micklh's answer, which works perfectly. However, it calculates the gradient based on two points, a starting point and an ending point. I want to change that such that I can give it a center point, an angle in degrees, and a length.

If you look at the picture from the other question:

You can sort of discern where the center point is, the x,y of starting/ending locations become the dots based on the length of the gradient.

I assume I would have to:

Take the center location
Apply the angle + length
Gives me my ending x,y
Take the center location
Calculate the reverse angle
Apply the reverse angle + length
Gives me my starting x,y
Plug these starting/ending positions to the answer from the other question.

Am I correct? How would I do those steps?


texts: Java code to get android phone hardware specs

texts: Is there code available to view the specs of a phone that is running your application?


texts:
I've read some articles about Entity Component System and I like this idea of "entities" having lots of "components" to define them, so I tried to implement it.
Here is an simple overview of what i've got so far:

I've a template class that will hold a list for each component type that exit

That allows me to have a collection of components by its type

Which is good because in memory components will be contiguous

Then I've a component manager that hold all these collections and allows me to retrieve a collection at any time

Also, each entity keeps tack of all components it has with a bitset

So in the final result, each index of all component containers belongs to an entity

I know that this causes a problem than, not all entities have all components, so it causes a waste of space... But for now, I can (saldy) live with it

But the real issue for me here is that some components will have same data, and if each entity have a component for that data, this data will be duplicated unnecessary

Even worst, it would require OpenGL to have different objects in memory that are exactly equal and having to enable those objects and disable them many times is not desirable at all.

I've been scratching my head to figure out a solution for this issue but I can't find any. Could someone give me an advice please?

If you've read this far, Thank You!


texts: How does one perform collision detection on objects made of many small triangles?

texts:
I understand that any shape can be created (or approximated) by smaller triangles.
Any rectangle can be created by 2 smaller triangles.
Any circle can be created by many thin "pizza slice" triangles. How does this translate to collision detection?

I understand how to calculate rectangle overlap using the vertices.
I understand how to calculate circle overlap using the center, radii, and distance.

But, how does one do collision detection on shapes made of small triangles?
Not specifics, but just the general concept....


texts: Draw a texture2D at specific coordinates on another Texture2D

texts:
I have a ShipTexture and a Sail Texture. I need to draw the sail texture at a specific location on the shipTexture (call it the sailMountPoint) regardless of the location vector associated with the ship. I.e. the sail should be mounted to the ship and move with it.

I have tried various methods calculating the offset from the vector2 location coordinates of the shipTexture, but am not really coming close. I have also put a color indicator (in the rgba data) in the texture where the sail mount is on the ship texture. During some pre-processing, I then calculated the offset from this position.

Something like the following:

    public class SailMountTextureCoordinates
{
    public static Dictionary<string, Dictionary<int, Tuple<int, int>>> SailMountCords = new Dictionary<string, Dictionary<int, Tuple<int, int>>>();
}

Preprocessing:

public Tuple<int, int> GetSailMountCords(Texture2D texture, int rows, int cols, string key)
        {
            Color[,] Colors = TextureUtility.TextureTo2DArray(texture);

            for (int r = 0; r < rows; r++)
            {
                for (int c = 0; c < cols; c++)
                {
                    // target frame on the texture
                    int width = texture.Width / cols;
                    int height = texture.Height / rows;
                    int X = width * c;
                    int Y = height * r;

                    for (int a = X; a < X + width; a++)
                    {
                        for (int b = Y; b < Y + height; b++)
                        {
                            //If we find a the red sail mount color
                                if (Colors[a, b].R == 255 && Colors[a, b].G == 45 && Colors[a, b].B == 0 && Colors[a, b].A == 255)
                            {
                                if (!SailMountTextureCoordinates.SailMountCords.ContainsKey(key))
                                    SailMountTextureCoordinates.SailMountCords.Add(key, new Dictionary<int, Tuple<int, int>>());
                                SailMountTextureCoordinates.SailMountCords[key][r] = new Tuple<int, int>(a-X, b-Y);
                            }
                        }
                    }
                }
            }
            return null;
        }

Mounting the sail:

        // set the sail location here (equal to ship location plus the offset on the texture to hit the mount)
        float offsetX = (0.5f * (float)(_texture.Width / nColumns));
        float offsetY = (0.5f * (float)(_texture.Height / nRows));
        shipSail.location.X = location.X - offsetX + SailMountTextureCoordinates.SailMountCords[bbKey][currRowFrame].Item1;
        shipSail.location.Y = location.Y - offsetY + SailMountTextureCoordinates.SailMountCords[bbKey][currRowFrame].Item2;

It is worth noting that I am using a large sprite sheet for both textures, then setting the source rectangle for the correct ship and sail frame.

Are there any easier ways to do this in monogame/XNA? So far I've had no luck with this route.


texts: What is the best practice for calculating a succesful action?

texts:
Say for example in my game a player is able to kill an NPC, and there is an x% chance of an item dropping.

When calculating if the item actually dropped or not, what is the best way to calculate a success or failure?

Does the context of the action matter? Would you calculate drop chance the same way as a different RNG event? (x% to gain a perk, etc).


texts: How to keep Input System and Graphics System separate?

texts: I want to keep Input System and Graphics System separate, but the Window Handler that's created by graphics component make everything really hard. How should I approach this situation?


texts: Detecting collision with walls (is this a good solution?)

texts:
I'm trying to make the collision smooth (it must open the animation, but not move the character).

I've implemented 'fake positions':

int step = 20;
fake_left_x = x-step;
fake_right_x = x+step;
fake_up_y = y+step;
fake_down_y = y-step;

While updating player position, I'm checking if fake positions are out of the screen. If yes - nothing happens.

Is this a good solution? What do you think?


texts: Making a Video Splash Screen for an Android Based Game

texts: I'm planning to make a video-based splash screen for the simple game app for Android under client's cigarette brand project. I was thinking if can this video file type, AVI, run on Android or not? Please suggest me.


texts:
Say I want to write a card game. I have a hand of cards and I want to be able to draw a smooth animation of a card moving from the hand to the table. I am looking for suggestions on how to elegantly represent the situation in data structures. Of course, I am not solely interested in cards, it seems to be a problem with more complex user interfaces in general.

The obvious representation of the hand is an array/list of cards. Given a rectangle in 2d space this hand is trivial to draw. When playing a card I can remove that card from the array and create a new structure that draws that card moving along any curve I like. The problem is then how the hand is drawn. In trivial implementation the hand in one instant shrinks in width by one card (as the array was replaced). Also, the selected card is now either above or bellow the hand (as it is drawn before or after drawing the hand), while a moment ago it was between the two cards next to it. These problems I'm not sure how to solve. They get even worse if trying to move several cards at once.

It would most likely work to make every card a separate body aware of it's position and movement in the plane (and possibly, the z axis to make overlaps work, as OpenGL allows this). It does seem like poor design to allow a system that almost always stays in a fixed shape too much flexibility. It also looks like a recipe for unexplainable bugs.

I would like to hear from someone who has done this, what is the best approach. To put it briefly, "specific and restrictive representation in data structures" versus "entirely free environment with some external limits".

Thanks a lot


texts: Do UV coordinates need correction for moving object?

texts:
The image above is a static capture of a dynamic OpenGL project I created in which I wrapped a NASA albedo, i.e., sans clouds, image on an OpenGL generated sphere.  In so doing, I also generated the UV coordinates associated with each vertex position.

This was an incremental learning effort in which I had already applied model matrix corrections to the vertex positions for the rotating and translating (orbiting) "Earth".

I was surprised to find that I did not have to apply a model matrix correction to the UV coordinates.

I have tentatively concluded that once the jpg image coordinates are associated with the corresponding vertex positions with the UV coordinates in the range of [0, 1], they are fixed and need no further correction.

Does that sound correct, or is there more to the situation?


texts:
I've looked through some A* pathfinding algorithm examples, but as far  as i know they work with grids  e.q -> http://qiao.github.io/PathFinding.js/visual/

But how can I use this algorithm in my 3D Engine(I'm using Unreal Engine 4)?


texts:
When I call my tile engine function, the amount of memory my program uses begins to spike at about 80 - 90 megabytes per second. The memory use continues to go up until the program crashes. The function is below.

After tinkering with it, I figured out that I could reduce this bricking to about 15 megabytes per second if I called SDL_FreeSurface every time I ran the function. But this confused me, because I thought that you are only supposed to use SDL_FreeSurface when the program exits so that the images don't continue to occupy the memory.

if I don't call SDL_FreeSurface before I blit the tiles, do the previously blitted tiles continue to exist?
If I don't how do I fix the aforementioned bug?

The edit I made to bring the memory bricking down to 15 megabytes per second is commented out.

SDL_Surface* loadedTile = NULL;
SDL_Surface* modelIMAGE = NULL;

void enviroment::blitTiles(SDL_Surface* windowENVIRO, int tileAmount, int tileType[], int tileXenviro, int tileYenviro, bool quitTiles)
{
    HDcounter = -1;

//if(loadedTile != NULL)
//{
//    SDL_FreeSurface(loadedTile);
//}

loadedTile = IBFobjectENVIRO.loadIMG("tileClipSheet.png");

        for(int tiles = 0; tiles < tileAmount; tiles++)
        {

            switch(tileType[tiles])
            {
                //Black square (unpassable)
                case 1: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 0, 0, 75, 75);

                        HDcounter += 1;

                        forbiddenX[HDcounter] = tileXenviro - 75;
                        forbiddenY[HDcounter] = tileYenviro;
                        forbiddenSpriteWidth[HDcounter] = 75;
                        forbiddenSpriteHeight[HDcounter] = 75;
                        forbiddenSpriteDepth[HDcounter] = 75;
                break;

                //Grey square
                case 2: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 75, 0, 75, 75);
                break;

                //Brown square
                case 3: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 150, 0, 75, 75);
                break;

                //Invisible square (unpassable)
                case 4: IBFobjectENVIRO.blitIMG(tileXenviro - 75, tileYenviro, windowENVIRO, loadedTile, 225, 0, 75, 75);

                        HDcounter += 1;

                        forbiddenX[HDcounter] = tileXenviro - 75;
                        forbiddenY[HDcounter] = tileYenviro;
                        forbiddenSpriteWidth[HDcounter] = 75;
                        forbiddenSpriteHeight[HDcounter] = 75;
                        forbiddenSpriteDepth[HDcounter] = 75;
                break;
            }

            tileXenviro += 75;

            if(tileXenviro >= level1ObjectENVIRO.level1Width)
            {
                tileYenviro += 75;
                tileXenviro = tileXenviro - level1ObjectENVIRO.level1Width;
            }
        }

    if(quitTiles == true)
    {
        SDL_FreeSurface(loadedTile);
    }
}


texts: using glew glviewport cannot get the correct proportion of a window

texts:
the generated window resolution is (1334, 750)
when i call glViewport(0, 0, 1334, 750); the whole window is filled,
but when i call glViewport(0, 0, 1334 / 2, 750); the result is as bottom:

the proportion is obviously wrong, anyone know what happened?


texts: Should I create a Lua wrapper classes for my C++ classes, or should I bind them directly?

texts:
I have a fairly standard architecture like this:

GameObjects have Transform, and can have Renderer, Rigidbody, Camera, LightSource, etc, and all of these classes have their corresponding methods.

GameObject has GetName, SetName, etc. and its own Transform.
Transform has GetPosition, SetPosition, etc.
Renderer has SetTexture, SetMaterial, etc. and references a Transform/GameObject.

If I want to implement Lua scripting using LuaBridge, and I would like to achieve an API similar to this...

function update()
    local gameObject = this()
    local renderer = gameObject:GetRenderer()
    renderer:SetTexture("Brick")
    local rigidbody = gameObject:GetRigidbody()
    rigidbody:SetMass(10)
    local transform = gameObject:GetTransform()
    transform:SetPosition(1, 10, -5)
end

...then which of these should I choose?

Solution A:

I bind every C++ class directly to Lua classes.

In this way I have to implement some extra scripting quality-of-life methods for the classes, so no big deal.
But it's not so easy to see whether a method is callable in Lua script, or is only available in native code. (for example I need to name method XYZ as LuaXYZ)
Methods which are only created so that scripting is made easier, are mixed with core functionality.

Solution B:

I create a wrapper class for every required class, like: Renderer->RendererHandler, Transform->Transform Handler, GameObject->GameObjectHandler, etc.

Lua and core functionality is separated, much easier to see what is the scripting API and what is not.
For every class I have to create another similar class which got a lot of methods, which are just calling the calling the same method in the wrapped class. Like GameObjectHandler->GetName() just calls GameObject->GetName()

Thanks in advance.

Summary:

In my opinion, Solution B is the best. That is the easiest to handle, the most transparent, and the most separated.
But I got lots of new classes and new dependencies, which messes up my clean architecture. Solution A makes expanding functionality much easier to handle (I dont have to create a lua interface class for new components).
But error handling is worse, because I don't have to care about if a scripter uses a NULL pointer (like a non existent component)
But if that happens due to my engine implementation I'll have to handle it seriously. (And how can I signal whether a NULL pointer in a method is "don't care type" or "serious problem" type?)
So currently I think that the best solution is this:

class GameObject {
   ...

   GetName()
   SetName()

   Lua_getName()
   Lua_setName()

   ...

I don't have to create "Lua interface" classes, and handle that mess that comes with it.
I directly bind the Lua functions to the classes, but I create new methods in that class for scripting purposes.
For example I implement GetName() for "InEngine" functionality, and a Lua_getName() which is bound to Lua functions and used only in scripts.
The problem here is that, yeah you can't call InEngine methods from Lua because it's not bound. But what about calling Lua_getName() instead of GetName()?

There is no compile check for that, and if the developer is tired and makes this mistake, it will be hell to debug that.


texts: Matching the 3ds max camera view in my game 1:1

texts:
I want to match 1:1 the 3ds max camera render with my 3d engine (DirectX 11, C++).

I believe that my mesh exporter (coded with MaxScript) works fine, I see the right shapes.

But something about the perspective, translation (of the camera) and/or rotation is not quite right - the scene looks similar, but not the same:

As you can see:

the window proportion and size is ok,
the mesh looks fine (I'm not interested with the materials or shading now, just the 1:1 match of view & perspective),
to get the better match, I had to translate the window (as you can see on the second image, the corner of one has some offset),
the rotation or rather perspective seems to be a bit wrong (note the smaller teapot on second image).

I guess I've missed something:

My object and camera are places in the same position as in 3ds max (3ds max is set to millimeters, engine don't use any units - e.g. camera is at [20mm, 10mm, 0mm] in 3ds max and [20, 10, 0] in game engine).
Game engine camera uses DirectX::XMMATRIX projection = DirectX::XMMatrixPerspectiveFovLH(DirectX::XM_PIDIV2, screenWidth / (FLOAT)screenHeight, 0.01f, 1000.0f); and the 3ds max camera is set to FOV = 90:

The position and orientation of the object and camera (camera has no rotation applied) are converted from 3ds max right-handed z-up coordinate system to engine's left-handed y-up coordinate system. The orientation is expressed in quaternion and it's transformed from one system to another with:

.

temp = q.z
q.z = q.y
q.y = temp

q.z = -q.z
q.x = -q.x
q.y = -q.y

What did I miss and should take into account when matching game engine view with 3d edition software like 3ds max?


texts:
What I want to have for my Monotouch 2D projects:
simple collision detection and collision polygons working with UIViews

Sounds simple, isn't it? I've evaluated a lot of engines available on the market, but none of them gives me this simplicity without unnecessary overrun in my projects.

Box2D, monogame/farseer or Cocos2d seems to be good enough, but I don't really want to drag all that functionality to have 2 simple algs.

The question is: is there anything like this out there, or should I go and implement all this myslef?


texts:
For about a week I've been trying to grasp the basics of collision, but I've been driven to the point of wanting to just give up on everything when it comes to collision. I just don't understand it. Here's my code so far:

 public static void ObjectToObjectResponseTopDown(GameObject actor1, GameObject actor2)
        {
            if (CollisionDetection2D.BoundingRectangle(actor1.Bounds.X, actor1.Bounds.Y, actor1.Bounds.Width, actor1.Bounds.Height,
 actor2.Bounds.X, actor2.Bounds.Y, actor2.Bounds.Width, actor2.Bounds.Height)) //Just a Bounding Rectangle Collision Checker
            {
                if (actor1.Bounds.Top > actor2.Bounds.Bottom) //Hit From Top
                {
                    actor1.y_position += Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height;
                    return;
                }
                if (actor1.Bounds.Bottom > actor2.Bounds.Top) //Hit From Bottom
                {
                    actor1.y_position -= Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height;
                    return;
                }
                if (actor1.Bounds.Left > actor2.Bounds.Right)
                {
                    actor1.x_position += Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width;
                    return;
                }
                if (actor1.Bounds.Right > actor2.Bounds.Left)
                {
                    actor1.x_position -= Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width;
                    return;

                }
            }
        }

Essentially what it does so far is correctly collides when the bottom of the first rectangle collides with the top of the second rectangle, but with the left an right sides it corrects it either above or below the tile, and when the top of the first rectangle collides with the bottom of the second rectangle, it slides right through the second rectangle.

I'm really not sure what to do at this point.


texts: making a game in 2D(C++). SDL or openGL? Or, why not both?

texts: I'm trying to make a platform game in 2D and I want to know what tool should I use to make it happen. I understand that I can use SDL with openGL. However, if I want to make a solid 2D platform game, should I use SDL? Or, openGL?


texts: Unity: Render 1st Texture to 2nd Texture

texts:
I want to pass the first texture through a shader and render it to a second texture.

The actual task is bit more complicated, as I then want to render the second texture back to the first texture also using a shader.

I have a terrible solution at the moment involving two cameras, two quads and two materials and two rendertextures. The output of Cam1 is rendered to Texture1 used in Material1 applied to Quad1. Quad1 is in the view of Cam2 rendered to Texture2 used by Material2 applied to Quad2. Quad2 is of course in the view of Cam1. I then have to alternate turning on and off the Cameras and the Quads. It works, but the solution is terribly complicated.

Please tell me there is a better solution. With WebGL I could do this simply by swapping source and target for the shader. I'm sure this can be done in Unity too, but I have no clue what to look for.


texts: How to directly set a value to an UI Image's alpha channel(not the percentage of rendering)

texts:
When you write the code bellow, it renders a percentage of an image's predefined alpha value (which you define in unity's inspector - for example if you define the alpha value of an image to 100, the code bellow actually makes it 25, when the scene is being rendered)

_image.GetComponent<CanvasRenderer>.SetAlpha(.25f);

How can i rewrite the code above, to directly set an alpha value? Thanks.


texts: I am trying to figure out if there is a way to achieve facet lighting in OpenGL ES 2.0 without extensions. I know it is possible if I don't used indexed vertices but I don't really want to do that because it is a bit wasteful. I have seen people use dFdx and dFdy to achieve this in the shader but unfortunately they are only avaible with extensions here. Are the other options or is there perhaps a way to implement these functions manually?


texts:
In a minecraft-like game I'm making, I get white edges on my cubes:

It is much more noticeable in darker textures. The textures are being setup like this:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

Any help?


texts: Monogame - SpriteFont Exception: Text contains characters that cannot be resolved by this SpriteFont

texts:
I'm trying to put text on the screen and if I put anything but an empty string I get "Text contains characters that cannot be resolved by this SpriteFont.\nParameter name: text"

_spriteBatch.DrawString(screenText, "A", new Vector2(0, 200), Color.Black);

screenText is the name of my SpriteFont variable.

<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:LocalizedFontDescription">

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Arial</FontName>

    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    <Size>6</Size>

    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    <Spacing>0</Spacing>

    <!--
    UseKerning controls the layout of the font. If this value is true, kerning information
    will be used when placing characters.
    -->
    <UseKerning>true</UseKerning>

    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    <Style>Regular</Style>

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->

    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    For localized fonts you can leave this empty as the character range will be picked up
    from the Resource Files.
    -->
    <CharacterRegions>
      <CharacterRegion>
        <Start>&#32;</Start>
        <End>&#32;</End>
      </CharacterRegion>
    </CharacterRegions>
    <!--
    ResourceFiles control the charaters which will be in the font. It does this
    by scanning the text in each of the resource files and adding those specific
    characters to the font.
    -->
    <ResourceFiles>
        <!-- <Resx>Strings.resx</Resx> -->
    </ResourceFiles>
  </Asset>
</XnaContent>

I did build and rebuild the spritefont file using the Content Builder.


texts: In modern AAA games with open environment and lot of static content (eg : crysis), how is occlusion culling performed?

texts:
Two ideas i have in mind :

1) Scene is rendered to a invisible buffer, using low resolution and low polygon count models (or even using only bounding volumes like cubes or spheres). The buffer is then checked to know what is visible or not. Before rendering the low resolution scene, some frustum culling could be applied, to already remove as much objects as possible.

2) A tool is run on the static map and will perform complex (and thus slow) ray tracing to know for some 3d positions on the map what is visible and what is not. All that information is then stored in a efficient way that can be user later at runtime (eg: an octree)
This solution would only work for static meshes (eg : building) not moving objects.


texts: How does one avoid hundreds of copies into a vertex buffer each frame?

texts:
Assume a Direct3D9-based 2D game, high resolution, very busy. Performance critical.

A particle system has 2,000 particles. They are scattered throughout the world with only a subset visible on screen at any time. Thus the global array of particles contains a lot of particles that won't be rendered this frame.

Obviously they should be rendered in one call in a vertex buffer. I use an index buffer as well.

The slow bit is in the copying all of the vertex data to the buffer. I actually do this twice: once to a big buffer, then as a single copy from the big buffer to the locked vertex buffer. Regardless, I'm looking at 2,000 iterations and maybe 200-500 memcpy() calls that shuffle 4 vertices at a time.

There must be a better way. Maybe copying them all, and changing the index buffer instead? Or just rendering them all and let the off-screen ones get clipped (I'm not sure this is scalable though)?

How do people normally handle this?


texts:
I am making a 2D scroller game where the player controls an airplane via the accelerometer  I would like to know if it is possible to scale in and to scale out the sprite/airplane using the accelerometer z axis. I would like to know how to do this to create a depth illusion.

Any suggestion, tutorial recommendation, and comments are appreciated.

Thanks.


texts: How to get a consistent behavior for a rigid body hooked platform?

texts:
Consider this platform made of RigidBody2D and PinJoint2D objects:

PinJoint2D setup is:

Softness = 0
Bias = 0.9

When I set the mass of the platform with high value, the structure starts to shake like this:

Why is this happening and how to fix that?


texts: How do I share a downloadable WebGL build in Unity?

texts:
When I make a WebGL build for my project, I get a folder that lets me click a .html to play my game in a browser.  Is there a way I can share a folder like this for playtesters?
I tried sending a .zip folder to playtesters, but they only got a Unity loading screen that didn't do anything.


texts: How to pre-configure a prefab in the editor for multiple similar buttons before instantiating them

texts:
Let me explain my problem with my concrete example. I have a button prefab. A button prefab has a lot of configurations: background color, background shape, background image, text, text color, button type, text size, background size, etc.
I have a few places where I use the button prefab. In some places I can just manually put the prefab into the scene in-editor and preconfigure a button. But there are other places where I need to instantiate a batch of buttons with almost the same configuration.
Sure, I could setup each of these buttons in code during the instantiation. But that seems cumbersome. So, what I did is I added a button prefab to scene. Then configured it as I wish. Then hid it in the scene. Then created a script with a reference to a GameObject and now instead of a prefab from a file explorer I put the hidden configured button in that reference. So, now during an instantiation I only need to change the enablement of the instantiated button instead of configuring it from code.
I am really eager to know if there is a better way to do what I am doing.


texts: Why are dungeons so often created subtractively rather than additively?

texts:
I'm having difficult deciding on how to procedurally generate a dungeon floor. The way I've been doing it so far is like so:

Populate list of Rooms with random height and width.
Place first room in list at (0, 0).
Add room to a temporary list of rooms that have been successfully placed.
Place next room adjacent to a room randomly chosen from the aforementioned temporary list
Keep repeating previous step until room is successfully placed then move onto the next room.
Repeat the two previous steps until all rooms have been placed.

After that the doorways between the rooms are created and various steps are taken to assure collision is working properly but my question is this: Why does it appear to be common practice to first create a large area of cells that all are 'filled in' and to then 'carve out' rooms and corridors rather than to generate dungeons my way? I'm not saying my way is better, I would be happy for someone to tell me what I'm doing wrong and why I should be doing it differently. I just find my way easier for managing the various rooms and cells within my dungeon. It also means I don't have a bunch of 'useless' cells on the other side of the dungeon walls doing nothing but hogging processing power - that's something I never understood.

I just want to a way of generating a dungeon which balances efficiency and design.


texts: Communicating between simulation and rendering in RTS

texts:
I've been creating an RTS game, and I'm a little unsure about how to deal with the above. Right now, I wish to control which units are visible to which players, and I've run into a little problem. Previously, I had three components- render, sim, and UI (untrusted scripted component). However, I'm beginning to believe that this is not the optimal architecture.

For example, given the task that only the relevant units should be visible from a given player's perspective, none of the above components are up to the job. The sim is player-independent, the renderer has no idea about players at all, and the UI can't be trusted. So I've come to the need to introduce a fourth component- a kind of Controller which communicates between the three components and correctly limits the information each one has access to.

Is this the normal approach? Or am I missing a trick when it comes to making the sim, UI, and renderer co-operate?


texts:
I am generating normals for each vertex in a standard 512*512 quad. Yet when I do using the following code:

public Vector3f[] normals(Vector3f[] surface){
Vector3f[] normals = new Vector3f[surface.length];
for(int i = 0; i<normals.length; i+=4){

    Vector3f n1 = surface[i];
    Vector3f n2 = surface[i+1];
    Vector3f n3 = surface[i+2];
    Vector3f n4 = surface[i+3];

    Vector3f p1 = n1.subtract(n2);
    Vector3f p2 = n3.subtract(n2);
    Vector3f p3 = n3.subtract(n4);
    Vector3f p4 = n1.subtract(n4);

    Vector3f norm1 = (p2.cross(p1)).normalize();
    Vector3f norm2 = (p4.cross(p3)).normalize();
    normals[i] = (norm1.add(norm2)).divide(2);
    normals[i+1] = norm1;
    normals[i+2] = (norm1.add(norm2)).divide(2);
    normals[i+3] = norm2;

    }
    return normals;
}

I get the following from this:

Any ideas what is causing this? Thanks in advance.


texts: Should a mesh consist of triangles or quads?

texts:
Currently I am a bit puzzled. I am writing my master thesis about procedural mesh and texture generation and for that I am writing a Blender Add-On to generate low poly planets with physical physically based rendering textures.

This blog (http://blog.digitaltutors.com/modeling-with-quads-or-triangles/) says that it's better to use quads instead of triangles and n-gons. The wireframe looks cleaner, subdivides are more logic and having edge loops. Another blog about this topic can be found here http://blog.digitaltutors.com/ngons-triangles-bad/

But I also read this Why do game engines convert models to triangles compared to keeping it as four side polygon which says that in the end everything is converted to triangles. So I would assume that it's better to use triangles from the beginning so that the engine doesn't need to convert quads to triangles.

And now I don't know if it's better to use triangles or quads.

I could think of it this way:

For modeling use quads, because it's easier to manipulate a quad-mesh.
When modeling is done convert to triangles and export the mesh. But I think this is altering the low poly art style.
Use in a Game Engine.

If I read the ngons-triangles-bad blog post it says that there could be render issues with triangles. So why do engines than convert the mesh to triangles?!

Am I missing something important?

Any advice or more info? Thanks!


texts: Is there a way to make a dynamic world such as a MMORPG horizontally scalable?

texts: Imagine a open-world of 500+ players with data changing as fast as 20 updates/player/second. Last time I worked in a similar MMORPG, it used SQL, so obvioulsy it couldn't query the DB all the time. Instead, it loaded all players from the DB to memory as C++ objects and used them. That is, it scaled vertically. Would it be possible to make that server horizontally scalable instead? Is there a database designed to support that amount of updates concurrently?


texts:
I am working on a simple Box2D game (with Qt), but my objects don't collide correctly:

As you can see on the picture, objects try to go through each other and slide over.

My b2World:

b2Vec2 gravity(0.0f, -9.8f);
world = new b2World(gravity);

How I add objects:

b2BodyDef bodyDef;
if (dynamic) bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(centerX, centerY);
body = world->CreateBody(&bodyDef);

b2PolygonShape box;
box.SetAsBox(width/2, height/2);

b2FixtureDef fixtureDef;
fixtureDef.shape = &box;
fixtureDef.density = 1;
fixtureDef.friction = 0.5;
fixtureDef.restitution = 0.2;
body->CreateFixture(&fixtureDef);

for drawing, ppm - pixel per meter, scene - QGraphicsScene, rect - QGraphicsRectItem:

rect = scene->addRect(getRect(centerX*ppm, centerY*ppm, width*ppm, height*ppm));

Function to get QRectF (it takes left and top coordinates, not center):

QRectF GRect::getRect(float32 centerX, float32 centerY, float32 W, float32 H)
{
    return QRectF(centerX - W/2, centerY - H/2, W, H);
}

And how I draw every object:

b2Vec2 position = body->GetPosition();
rect->setRect(getRect(position.x*_ppm, position.y*_ppm, _width*_ppm, _height*_ppm));
rect->setRotation(body->GetAngle());

I tried to play with density, friction and restitution values, but it has no effect. Help.
PS. Sory for bad English, I am from Russia


texts: Platform independent replacement for LuaInterface

texts:
I'm currently working on a project in C#/XNA, however I'm planning to migrate this to MonoGame so that it can go onto more platforms. The problem is that I am currently using a lot of Lua, and for that in XNA, I am using LuaInterface.

The issue I now have is that LuaInterface only runs on Windows because of the dlls that it requires, but I would like to make this project available on Linux and Macs as well. Does anyone know of a good alternative to LuaInterface that could slot into Mono quite nicely?

Re-writing the parts which are currently in Lua in another language wouldn't be too much of a problem, but I need to be able to use scripting as I want to make large portions of my game open to players for modding.


texts:
Is there a way to get a scrollable container in Unity without purchasing a plugin such as NGUI or TK2D?

I want to create a scrollable container of interactive elements that can be clicked on individually and be scrolled horizontally by the user dragging their finger. You can kind of think of this as something similar to the shop menus in Clash of Clans. Here's a quick mock that I made to demonstrate the behavior I'm looking for: https://www.youtube.com/watch?v=bOJSMDPdFUQ

Is there a built in way to do this in Unity without the need of purchasing an extra plugin such as NGUI or TK2D?


texts: What is a library for event-driven mouse and keyboard input in Java?

texts:
The title basically says it all.

The only thing to take into consideration is it needs to be cross platform.


texts: Pitch becomes yaw as camera gets near object

texts:
I have been having trouble with my camera, first encountering the roll tilt that is so many times asked... I fixed that issue by following the instructions at this link: Unwanted roll when rotating camera with pitch and yaw But now I find another issue, whenever I get close to my triangle, pitch becomes roll, and instead of moving up and down the triangle, the camera rotates around the plane of that triangle, see:

This is my code, I follow the same logic as the link above!

  float spitch = pitch * camera.sensitivity, syaw = yaw * camera.sensitivity;
  float npitch = Math_Quaternion_GetPitch(camera.rotation) + spitch;
  if(npitch > Math_Degrees_ToRadians(85) || npitch < Math_Degrees_ToRadians(-85)) return;
  Math_Quaternion yaw_quat;
  Math_Quaternion pitch_quat;
  Math_Vec3 up = {0, 1, 0};
  Math_Vec3 left = {1, 0, 0};
  Math_Quaternion_RotationAroundAxis(yaw_quat, up, syaw);
  Math_Quaternion_MultiplyVec3(left, camera.rotation, \* this is out! *\ left);
  Math_Quaternion_RotationAroundAxis(pitch_quat, left, spitch);
  Math_Quaternion_Multiply(pitch_quat, camera.rotation, camera.rotation);
  Math_Quaternion_Multiply(yaw_quat, camera.rotation, camera.rotation);
  Math_Quaternion_Normalize(camera.rotation);

Edit: Also, switching the quaternion multiplication order or just using a normal pitch yaw roll method fixes the problem, but then the roll problem comes back!


texts:
I'm pretty New to the XNA Side of things,

I have built in PhotoShop a Set of frame by Frame images side by side to go through an animation class to display them frame by frame.

With this my images will not show up properly, they look more like a film reel.

Were could I Ggt good information on images for animation for XNA?


texts: Defining collision response in an Entity system

texts:
I'm building a really simple top-down 2d shooter which uses an Entity Component pattern.

I've added several different entities to a level and given them different collision groups. I have an entity to represent a teleporter (assigned to collision group A), a player entity (group B), and a bunch of enemies (Group C).

I understand that the actual collision response should be decided in the collision System based on the groups that the colliding entities belong to. What I can't figure out is how to define the specifics of a collision.

For example, if a player collides with a teleporter I need to move the player across the level. Where do I store the target location? I'd assume in a component on the teleporter. Should I create a whole new component just for that data? I feel it should be stored in the teleporters collision component but no all entities that use the collision component will require this data.

Could someone please try to enlighten me?

Thanks


texts: Trying to convert as3 Matrix to C++ glm matrix

texts:
I am trying to convert a library called DragonBones to C++ Opengl which allows you to use Flash based skeletal animation. I'm almost done but I am running into a problem. I am trying to transform the parent bone with the child bone when I load in the data. The as3 code(Im using hardcoded numbers to factor out any other problems) is

var matrix:Matrix = new Matrix();

    matrix.a =  1 * Math.cos(120);
matrix.b =  1 * Math.sin(120);
matrix.c = -1 * Math.sin(120);
matrix.d =  1 * Math.cos(120);
//Parent Point
matrix.tx = 10;
matrix.ty = 10;

var _helpPoint:Point = new Point();

//Child Point
_helpPoint.x = 40;
_helpPoint.y = 50;

matrix.invert();

var newPoint:Point = new Point();

newPoint = matrix.transformPoint(_helpPoint);

trace(newPoint.x)
trace(newPoint.y)

It comes out with x being 47.64987648428943 and y being 15.148903294693044

Now for GLM here is the code:

float a =   1 * cos(120);
float b =   1 * sin(120);
float c =  -1 * sin(120);
float d =   1 * cos(120);
float tx =  10;
float ty =  10;

glm::mat3 parentMatrix = glm::mat3(a,b,0,c,d,0,tx,ty,1);
glm::vec3 childPoint = glm::vec3(40,50,0);
parentMatrix = glm::inverse(parentMatrix);
glm::vec3 finalpoint = parentMatrix * childPoint;
printf("Final Point is %f, %f \n", finalpoint.x, finalpoint.y );

Which comes out to be X:61.597794 Y:17.484602

I think there is something wrong when I am multiplying the parentMatrix and childPoint because if you set the tx and ty to 0 in the as3 code it comes out with the same output as anything you put in tx and ty for glm. So for some reason the tx and ty in glm is not factoring into the equation. Does anyone know what I am doing wrong? Thanks in advance


texts: How can I create a custom PropertyDrawer for my Point struct?

texts:
I created a Point struct:

[System.Serializable]
public struct Point
{
    public int x;
    public int y;
}

I am trying to create a property drawer for it, so that when it shows in the inspector, it is shown in a Vector2 field.  I have the following script in the "Editor" folder:

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(Point))]
public class PointEditor : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.Vector2Field(position, label, property.vector2Value);
    }
}

It shows up in the inspector the way I want, but the values are locked at 0. Basically, I am trying to access the Point instance from inside the OnGUI method, but this could be the completely wrong approach. How can I make this so that when the values are changed in the inspector, the respective Point is also changed?


texts: What is the term for a 3x3 tile set used to create larger areas?

texts:
What is the pattern/design name of using a 3x3 tileset (usually in a tiled 2D game) that can be used to create larger areas of itself. For example, these:

(Image source)

I thought it was a "9 tree" or something like that but cannot find it, it is perhaps an uncommon reference.


texts: How can I make an inventory system in Unity?

texts:
I am trying to make an inventory system for the game I'm working on with Unity and I want it to expand and compress whenever objects are added or removed.
Is there any go-to way to do this?


texts: In Unity how can I know which direction is the screen auto-rotated?

texts:
From the Screen.orientation description I get

  If the value is set to ScreenOrientation.AutoRotation then the screen will select [...] automatically as the device orientation changes.

This seems to imply that if the screen does auto-rotate, then Screen.orientation has been set to ScreenOrientation.AutoRotation.

If that's so, how can I know in which direction it has been auto-rotated?

Disabling the auto-rotation doesn't count (obviously), and I need to distinguish between LandscapeLeft and LandscapeRight, so checking height and width doesn't work either.

This should be cross-platform, without including any kind of non-C# plugin.

(the answer, given this documentation, seems to be "you can't", but maybe I'm missing something)


texts: Why do game developers develop games for exclusive contracts?

texts:
There are several companies that develop their games for one console only (Playstation or XBox). Why and how are they doing this? Shouldn't there be more sales when they publish it for PC/PS/Xbox?

Why are they signing such contracts? What are the benefits?

Note: As long as these games are full funded by the console company I totally understand this exclusivity - but are there cases where these companies do not fund a game and it is still exclusive?


texts: Can I (safely) assume that people playing my game have a middle mouse button?

texts:
The title pretty much says it all.

I am currently writing a desktop game, which will probably not be played by the casual gamer. Thus my expectation is that nearly every user will most likely already have a mouse with a scroll wheel + button. Is that true?

This question is for "gamers" - I don't care if my grandmother's laptop doesn't have that button.

(Of course I know that I should think about a system that allows to change the input settings to make the game playable - even without a third mouse button.)


texts: Singleton Pattern & global var access alternatives

texts:
I know this is a controversial topic being discussed a lot , but I have not found a clear answer yet.
So , there is a "Grid" in my game , which I implement it with an Array of GameObjects. This array should be accessed by different scripts in my game. My approach , is that I have a Game Manager , which is a Singleton , the array is public , and every script that needs to access it or make a change can do something like GameManager.Instance.GridArray[i,j]; .
Using singleton and public variables are heavily criticized for extensibility and coupling issues. What approach would be better for this situation ?


texts: Exception when opening new libgdx project in intellij

texts:
I'm trying to learn Libgdx and I used the project creator to create a project with the default settings. I then try to open the build.gradle in the root of the project and I keep getting an exception. Anyone know what is causing this and how I can open the project?

Intellij 2018.1.4

  java.lang.NullPointerException at com.android.tools.idea.project.messages.AbstractSyncMessages.removeMessages(AbstractSyncMessages.java:79) at com.android.tools.idea.gradle.project.sync.messages.GradleSyncMessages.removeProjectMessages(GradleSyncMessages.java:50) at com.android.tools.idea.gradle.project.sync.idea.notification.GradleNotificationExtension.customize(GradleNotificationExtension.java:57) at com.intellij.openapi.externalSystem.service.notification.ExternalSystemNotificationManager.createNotification(ExternalSystemNotificationManager.java:168) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil.createFailureResult(ExternalSystemUtil.java:651) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$3.onFailure(ExternalSystemUtil.java:517) at com.intellij.openapi.externalSystem.service.remote.ExternalSystemProgressNotificationManagerImpl.onFailure(ExternalSystemProgressNotificationManagerImpl.java:124) at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:94) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:163) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:149) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3.execute(ExternalSystemUtil.java:542) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$4.run(ExternalSystemUtil.java:605) at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:750) at com.intellij.openapi.progress.impl.CoreProgressManager$5.run(CoreProgressManager.java:434) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:157) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:580) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:525) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:85) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:144) at com.intellij.openapi.application.impl.ApplicationImpl.lambda$null$10(ApplicationImpl.java:565) at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:305) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)


texts: How can I efficiently change the color of a BufferedImage?

texts:
I am trying to change the color of a white BufferedImage image.

I do know that you can use .setRGB(x,y,rgb) and simply run some nested for loops and make changes to one pixel at a time. However, the problem arises when it comes to gradually changing the color instead of instantly doing so. This means I would have to run thousands of loops every runtime, completely ruining the frame rate.

My question is, is there a way to just change the color of an image right away?


texts: Channelling an explosion along a narrow passage

texts:
I am simulating explosions in a 2D maze game.

If an explosion occurs in an open area, it covers a circular region (this is the easy bit.)

However if an explosion occurs in a narrow passage (i.e narrower than the blast range) then it should be "compressed", so that it goes further and also it should go around corners.

Ultimately, unless it is completely boxed-in, then it should cover a constant number of pixels, spreading in whatever direction is necessary to reach this total area.

I have tried using a shortest-path algorithm to pick the nearest N pixels to the origin avoiding walls, but the effect is exaggerated - the blast travels around corners too easily, making U-turns even when there is a clear path in another direction.  I don't know whether this is realistic or not but it is counter-intuitive to players who assume that they can hide around a corner and the blast will take the path of least resistance in a different direction.

Is there a well-known (and fast) algorithm for this?


texts: Calculating price increases in a virtual economy

texts:
I'm trying to design a method to have price increase depending on the number of items bought from shops in my game.

I'm fairly new to coding and I am struggling to figure out how to program the increase in price when buying multiple items.

Currently the price increase is a percentage increase based on the quantity of items in store, however if I buy 5 items, all 5 items will be charged the same. How can I get it so each item is charged at a different price?

I also need a reasonable inflation system, right now my code just determines a price increase based on the percentage of items remaining, but it's very simple and easy to exploit.
It looks like this:

30 - 2 = 28

1 - (28 / 30) = 0.07  0.93

1 + 0.07 = 1.07

10 * 1.07 = 10.7

Rounded up

Price = 11

I'd like to make this more complex also.


texts: What FOV does Unity show in a 16:9 aspect ratio, when set to FOV 60?

texts:
Preamble:

I noticed the FOV in Unity is only correct when the screen resolution is square, in other words when the width of the screen is the same as the height.

When you add more width to the screen, the camera shows a greater FOV sideways. (The FOV remains the same up and down.)

To see this is true, set the resolution to be square, set the FOV to be 90, and go into a corner and look out and compare the positions of both walls: They will match the sides of the screen.

So even 4:3 screens show more FOV. 16:9 shows way more. I am not sure of the math to determine how much.

Question:

I wonder what aspect ratio shows a FOV of 90 (sideways) when it is set to the default 60? Does anyone know the math?


texts: Update total enemy counter after single enemy is defeated?

texts:
So I have a list that counts how many enemies are in the area. But when I kill an enemy, the list shows that that element in that array is missing, and doesn't reduce the enemy counter. How can I get it to reflect when an enemy is defeated?

Code:

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

public class EnemyCount : MonoBehaviour {
public List<Transform> enemies;

void Start () {
    enemies = new List<Transform>();
}

void Update () {
    FindAllEnemies();
}

public void FindAllEnemies () {
    GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");

    foreach (GameObject enemy in go) {
        //Checks for duplicates
        if (!enemies.Contains(enemy.transform)) {
            AddEnemiesToList(enemy.transform);
        }
    }
}

public void AddEnemiesToList (Transform enemy) {
    enemies.Add(enemy);
}
}


texts: When importing Mixamo animated characters into Unity, they come without avatar?

texts: I'm using Unity 2019.3.3f1. I create the character in Adobe Fuse. I uploaded it to Mixamo and choose an animation. I then downloaded the fbx for unity file. When imported into Unity, it is visible that the file has no avatar or animator component. How can I fix this? Is it a Unity version issue?


texts: Why does my object move faster at 45 degrees than at 90 degrees?

texts:
I have objects in my game that move faster at 45 degrees then at 90 degrees.

Each object has

Point (x,y) position
Vector2D (x,y) direction
Int speed

And what I do during a update is that new position is calculated as:

position.x += direction.x * speed
position.y += direction.y * speed

How do I correct this? I want it to move with the same speed at any angle.


texts: How to transfer a variable from script to another in Godot

texts:
I have 3 sprites A, B and C, each one has area2d attached to it and collision shape

the script for A

extends Area2D
var done = 0

func _input_event(viewport, event, shape_idx):
    if event.type == InputEvent.MOUSE_BUTTON \
    and event.button_index == BUTTON_LEFT \
    and event.pressed:
        get_parent().hide()
        done = 1

And all like that

Now the main node has a script attached to it

extends Node2D

func _ready():
    if get_node("lA").get("done")==1 && get_node("B").get("done")==1 && get_node("C").get("done")==1:
            get_tree().change_scene("res://scenes/scene2.tscn")

But it doesn't work, why?

The error when doing if get_node("lA").done == 1 is

Invalid get index 'done' (on base: 'Sprite').

What I'm trying to do is collect some items, when done, move to a new scene


texts:
I'm trying to get an outline like effect shown on the right in this video. Using fresnel seems to make the whole thing go white at certain angles. How do I prevent that?
I'm using amplify to make this. Here's my current setup


texts: How to deal with variable size font in XNA 4.0

texts:
After searching for a while, I found no way to draw vector/scalable fonts in XNA 4.0 (which would be perfect...) and I am currently in a bind about how to render fonts for my game.
In the game I use fonts of variable size, ranging from very small to quite large, and I have no idea how to efficiently deal with this.

The only way I can currently accomplish what I want is to load a large number of SpriteFonts different sizes, manually pick the font closest to the size I want, and then fine-tune the size with a scale close to 1. (A scale too large or too small will make the font look horrible.)
I've also started using the Nuclex font processor which makes the fonts looks somewhat better, but it's obviously not the answer to my problem.

Is there really no other way to deal with this?
It seems very strange to me that something as elaborate and well done as XNA 4.0 has such a profound lack of tools to deal with font rendering.

This is quite a big problem for me currently, so any help and ideas on possible ways to deal with this or even to ease the pain are very welcome.


texts: How is collision working in UE4 Free Asset Paragon-Kallari? It seems like the body of the character and the cape is somehow colliding but I wasnt able to find any physics asset or any setting. Could someone help me with this?


texts: Unity: Disable push on dynamic Rigidbody2D objects

texts:
I have a player, and several NPCs.
I also have several static colliders in the world (trees, water, fence, etc), I want my NPCs to collide with this, so the Rigidbody2D needs to be dynamic, since kinematic does not collide with static colliders (colliders without a rigidbody).

My problem is that since both player and NPC have dynamic rigidbodies, they push each other when they collide.
I could disable this by setting the following in the NPC script:

void OnCollisionEnter2D(Collision2D other){
    if (other.gameObject.name == "Player") {
        isMoving = false;
        myRigidBody.isKinematic = true;
    }
}

However, the NPC still gets pushed a few pixels before it stops, its barely noticable, but it is noticable, and if you keep colliding with the NPC you could move it as far as you wanted (tedious, but possible).

I've spent a few hours looking and cannot find a good solution to this.
I want my NPC to collide with static colliders, but I don't want them to get pushed by the player. How can I solve this?


texts: Generate random vector relative to current vector within a certain degree in 3D space

texts:
I'm creating a simple ray tracer and I think this would be the best place to ask. I've created my own engine in Go, and I've gotten pretty far. I am now implementing diffuse surfaces, so I'll need to generate a random direction to send scattered rays to fake diffuse.

I've looked at the other questions on here, and I found that was similar to my question, but it was for 2D space, and not 3D.

Let's say I have a direction a, and I want to generate a new direction that is random, and within 45 degrees of direction a. Since I'm working in 3D space, I can't simply find the perpendicular angle and lerp between them, so I'll need to do something different. For example, this is what I'd do in 2D:

dir = Vector2(1, 1).Normal()

perpDir = dir.Perp() // gets the perpendicular direction of `dir`

randDir = dir.Lerp(perpDir, rand() - 0.5) // rand is [0, 1)

I'm not very knowledgeable when it comes to math, so this needs to be pretty dumbed down for me to understand. Is there any simple way to find a random direction based on a current direction with a maximum rotation of a set maximum rotation like 90 degrees?


texts: How do I sort isometric sprites into the correct order?

texts:
In a normal top-down 2D game one could use the screen y axis to sort the images. In this example the trees are properly sorted but the isometric walls are not:

Wall 2 is one pixel below wall 1 therefore it is drawn after wall 1, and ends up on top.

If I sort by the isometric y axis the walls appear in the correct order but the trees do not:

How do I do this correctly?


texts: Help comparing Cocos2d and Unity3d for this project

texts:
I will not go into details, but I would like to hear your opinions about this:

Essentially, my project will be a 2d game, with lots of complex levels, where some might be simple and others might be a bit more deep, with physics, etc. We want to implement our very own online structure: logging in, leaderboards, achievements, friends etc with our own servers. This means no OpenFeint nor GameCenter at all. We expect this game to be very large in both graphics and audio. We wish to use in-app purchases.

Now, we considered two options. Cocos2d and Unity3d.

We need help deciding using the factors I mentioned before (networking, good performance even for a large game in terms of graphics and audio like this, in-app purchases, etc) which option would fit better this?

Technically, both options can create 2d games. I'd like to hear your opinion.