texts: Is restitution the wrong value, to make bouncing objects?

texts:
I have been experimenting with Bullet. Specifically I was modifying the Hello World tutorial, to make the ball bouncing.

The first thing I noticed is, that I need to set  both the restitution of the ball and the ground above 0 to make the ball bouncing.

For a simple setup, with two objects, this seems fine. However, for larger simulations I fell like, restitution is the wrong way, to make bouncy objects. Here are my reasons:

Reason 1

Consider three objects: ball, box and ground. ground is just some plane. box is a box, which is not supposed to be very bouncy, thus its restitution is near or equals zero. ball is supposed to be bouncy, so I give it a restitution of 0.5.

If now the ball collides with the ground, it only actually bounces, if the ground also has a restitution higher than 0, so let's give it a restitution of 1. So our ball is bouncy as expected, when colliding with the ground.

When it collides with box it won't bounce, because the box has a restitution of 0. If we give box a higher restitution, the ball will bounce from it. But now we have a different problem. If the box collides with the ground, it will bounce off, but it isn't supposed to.

I see no way, with restitution only, to make this scenario work.

 Reason 2

Restitution describes the amount of energy, that remains as impulse after a collision. The rest of the energy goes into deforming the colliding bodies and other side effects.

If we now look at a typical bouncy object, like a rubber ball, we see that they are easily deformable (compared to less bouncy objects). When the rubber ball collides with something, it takes up energy from the collision, by being deformed and then goes back into its original form, thus releasing the energy taken up during the collision and bouncing back off.

 The solution (?)

Reason 2 suggests, that a bouncy ball (like a rubber ball) shouldn't have a restitution close to 1, but rather be elastic (thus being deformed and then going back to its original form), to model bouncy objects as expected.

The way to model this in Bullet, would be a soft-body and I think it would be the way to go, in such a scenario.

 The actual question

The text above looks more like an answer than a question, so here's the question I'm trying to ask:

I'm really unsure, whether this is right. Are soft-bodies really the better way for bouncy stuff or am I just mistaking the principle of restitution?


texts: Entity polymorphism and entity attributes

texts:
I want to design the entity system of my game in a way such that entities are modular, easily modified without affecting other entities, and finally easy to add new types of entities. So ideally some version of component based design.

In some parts of the code I want to deal with entities generally and abstractly, for example "update all entities" and "render all entities", however in other parts I want to deal with specific types of entity, like when a Soldier entity is fighting a Tank entity.

The problem is some entities need attributes which others do not. For example a soldier needs HP but a missile do not.

How do I keep entity attributes modular, and avoid adding every attribute in the game to the Entity object?


texts:
I am currently trying to combine both slick2d and nifty to work together. I've had some amount of success - I can now actually run my test and it won't crash. As far as I can tell, it will also receive input properly.

First, I'm having doubts I'm doing it right. I extend NiftyStateBasedGame in my outer game and then I extend two NiftyOverlayGameState to create the two states. However, I am getting an error that doesn't crash my application saying:

WARNING: An event service by the name NiftyEventBusalready exists.  Perhaps multiple threads tried to create a service about the same time?
org.bushe.swing.event.EventServiceExistsException: An event service by the name NiftyEventBusalready exists.  Perhaps multiple threads tried to create a service about the same time?
    at org.bushe.swing.event.EventServiceLocator.setEventService(EventServiceLocator.java:123)

I could ignore it, since the application is running well enough (I think?) but I'm concerened that once I figure out how to actually implement some parts of the GUI they might not work.

Which leads me to my next question. I was trying to create a simple button on screen and I could not for the life of me figure out how to go about it. I have my nifty instance... But what do I do with it? Any pointers in the right direction would be greatly appriciated!

My three classes:

The outer class, TheGame (This is the StateBasedGame)

public class TheGame extends NiftyStateBasedGame
{

    Menu menu;
    Nifty nifty;
    GameOver go;

    public TheGame(String name)
    {
        super(name);
        menu = new Menu();
        go = new GameOver();

    }

    @Override
    public void initStatesList(GameContainer arg0) throws SlickException
    {
        this.addState(menu);
        this.addState(go);

    }

    public static void main(String[] args) throws Exception
    {
        AppGameContainer game = new AppGameContainer(new TheGame("OMG, Super test!"));

        game.setDisplayMode(800, 600, false);
        game.setAlwaysRender(true);

        game.start();

    }

And the two dummy classes the are the states:

public class Menu extends NiftyOverlayGameState
{
    @Override

    protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException
    {
        initNifty(gc, sbg);
    }

    @Override
    protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException
    {
        g.drawString("Does it work?", 100, 100);

    }

    @Override
    protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
    {
        Input input = gc.getInput();
        if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON))
            sbg.enterState(1);
    }

    public int getID()
    {
        return 0;
    }

public class GameOver extends NiftyOverlayGameState
{

    protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException
    {
        initNifty(gc, sbg);
    }

    @Override
    protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException
    {
        g.drawString("WORKS, OOOH-YEA!", 100, 100);
    }

    @Override
    protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
    {
        Input input = gc.getInput();
        if (input.isMouseButtonDown(Input.MOUSE_RIGHT_BUTTON))
            sbg.enterState(0);
    }

    public int getID()
    {
        return 1;
    }

Again, if compiled, this gets me the two screens I want with the warning/exception I mentioned above. What am I doing wrong? And how would I start actually adding GUI elements to this?


texts: What is causing my skybox texturing issue?

texts:
I am using the NVIDIA cubemap tool to generate my .dds file in Photoshop but I am unexpected results when the texture is loaded into my application.

I'm unsure as to whether this is caused by my code, or the texture generation in Photoshop. Does anyone know why this is happening?

The texture is being applied to a sphere and it seems to only be stretching down the centre of the sphere, the rest is ok.

The code I am using to generate the resource view

D3DX11_IMAGE_LOAD_INFO loadSMInfo;
    loadSMInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
    loadSMInfo.BindFlags = D3DX11_DEFAULT;
    loadSMInfo.Depth = D3DX11_DEFAULT;
    loadSMInfo.Filter = D3DX11_DEFAULT;
    loadSMInfo.FirstMipLevel = D3DX11_DEFAULT;
    loadSMInfo.MipFilter = D3DX11_DEFAULT;
    loadSMInfo.MipLevels = D3DX11_DEFAULT;

    ID3D11Texture2D* SMTexture = 0;
    hr = D3DX11CreateTextureFromFile(_pd3dDevice, L"assets/textures/skybox/sky.dds",
        &loadSMInfo, 0, (ID3D11Resource**)&SMTexture, 0);

    D3D11_TEXTURE2D_DESC SMTextureDesc;
    SMTexture->GetDesc(&SMTextureDesc);

    D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
    SMViewDesc.Format = SMTextureDesc.Format;
    SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
    SMViewDesc.TextureCube.MipLevels = SMTextureDesc.MipLevels;
    SMViewDesc.TextureCube.MostDetailedMip = 0;

    ID3D11ShaderResourceView * smrv;
    hr = _pd3dDevice->CreateShaderResourceView(SMTexture, &SMViewDesc, &fullcubemap);

Edit: I have changed the sphere to a cube and the texture is looking better quality on two of the faces, but the other faces are stretched and distorted. I'm going to try another texture.

https://i.gyazo.com/6d4556bd79b0e3adce156e631fb2f514.mp4

Edit: I believe the problem is in my shader, forgetting to set the w value on the position to 1.0f.

https://i.gyazo.com/e1fd41679e2257920aebff8d4c766118.mp4

Perhaps the only problem left is a wrong texture image?


texts: Splitting into files - how much splitting?

texts:
If I say I have a hierarchal entity framework, rather than a component model. Something like:
(Yes, this is made up)

Weapon->Gun->AutomaticGun->MP44
Or, more of a classical example:
Entity->MovableEntity->Enemy->WalkingEnemy

How far would you split up the source/header files for readability and organization? Is it best to go something like Entity.cpp, MovableEntity.cpp, Enemy.cpp, etc. or would an approach like Entity.cpp [containing Entity and MovableEntity] and Enemy.cpp [containing Enemy and WalkingEnemy] be better?  (Or in a more language agnostic way, an Enemy file and an Entity file vs a file for each class?)
Also, would this affect anything other than readability and organization?


texts:
What's the best way to have large animations in XNA 4.0? I have created a spritesheet with the sprite being 250x400 (more of an image than a sprite but hey ho) and there are approximately 45 frames in the animation. This causes problems for XNA as it says that the maximum filesize for Reach is 2048.

I'd rather not change to hidef as I heard that means that your game is less compatible with some computers and systems so does anyone have any idea what the best thing I could do is? The only thing I could come up with is to have a list of textures to flick through but that's not ideal.


texts: Any ideas on reducing lag in terrain generation?

texts:
Ok so here's the deal. I've written an isometric engine that generates terrain based on camera values using 2D perlin noise. I planned on doing 3D but first I need to work out the lag issues I'm having. I will try to explain how I am doing this so that maybe someone can spot where I am going wrong. I know it should not be this laggy.

There is the abstract class Block which right now just contains render(). BlockGrass, etc. extend this class and each has code in the render function to create a textured quad at the given position.

Then there is the class Chunk which has the function Generate() and setBlocksInArea(). Generate uses 2D perlin noise to make a height map and stores the heights in a 2D array. It stores the positions of each block it generates in blockarray[x][y][z]. The chunks are 8x8x128.

In the main game class there is a 3D array called blocksInArea. The blocks in this array are what gets rendered. When a chunk generates, it adds its blocks to this array at the correct index. It is like this so chunks can be saved to the hard drive (even though they aren't yet) but there can still be optimization with the rendering that you wouldn't have if you rendered each chunk separately.

Here's where the laggy part comes in:

When the camera moves to a new chunk, a row of chunks generates on the end of the axis that the camera moved on. But it still has to move the other chunks up/down in the blocksInArea (render) array. It does this by calculating the new position in the array and doing the Chunk.setBlocksInArea():

for(int x = 0; x < 8; x++){
     for(int y = 0; y < 8; y++){
         nx = x+(coordX - camCoordX)*8
         ny = y+(coordY - camCoordY)*8
         for(int z = 0; z < height[x][y]; z++){
             blockarray[x][y][z] = Game.blocksInArea[nx][ny][z];
          }
       }
}

My reasoning was that this would be much faster than doing the perlin noise all over again, but there are still little spikes of lag when you move in between chunks.

Edit: Would it be possible to create a 3 dimensional array list so that shifting of chunks within the array would not be neccessary?


texts: Unity3D position of 2D objects with size of Object

texts:
I'm making a 2D project in Unity3D.
I want to place an image in the right upper corner.
I've got this working, but ofcourse the image is falling of the screen for a part (and completely when I change the screenrotation).

This is the code I've got for it;

posImage = new Vector2(Screen.width - imgGear.transform.localScale.x, Screen.height - imgGear.transform.lossyScale.y );

As you can see in the code I've tried to adapt the position with the size of the object, using localScale 1.0f and lossyscale 0.9...f doesn't really do much as it will be changed with 1 unit.
Is their a way to get the real width and height of the objects?


texts:
I have game situation as shown in picture:

Red dot: player
Brown dot: obstacle ( rock, tree, etc)
Grey: non visible area ( under fog of war)

My question is: how can I draw that kind of shape, changed dynamically, with XNA 4.0. I can calculate each point of this shadow polygon. I would avoid drawing it pixel by pixel due to performance reasons, maybe particles? But i won't have sharp edges with this technique. Any tips?


texts:
I have a button I got from google material design asset pack which has a ripple animation when pressed. I'm using the button's click option in the inspector that calls a method that switches scenes. But when I tap the button it switches the scene immediately and feels unnatural since the animation hasn't finished the button ripples animation.

I tried using co-routines. Made the button call a method in which I call a IEnumerator method (since the button can't directly call a co-routine) and then switch the scene. But that doesn't work since it starts the co-routine and switches the scene, the co-routine never pauses the code and never finishes (probably because I loaded a new scene and the object that carries the script isn't transferred).

Code example:

The method that gets called when I tap a button:

 public void OnButtonTap()
 {
     StartCoroutine(Wait(0.2f));
     SceneManager.LoadScene("OnePlayerGameIntro");
 }

The wait coroutine:

 public IEnumerator Wait(float seconds)
 {
     yield return new WaitForSeconds(seconds);
 }


texts: How do i make enemy tank to follow and face player tank?

texts:
I'm creating tank game demo , in game i want enemy tank to always face toward the player tank.

I already check look_at() function but it will face immediately, i don't want that. I want enemy tank to slowly rotate toward player.

What i'hv done so fare is :

MainWindow.gd

extends Node2D

func _ready():
    $Tank2.loadPlayer1($Tank1)
pass

EnemyTank.gd

extends KinematicBody2D

var rotSpeed = 0.3

var player1

var speed = 30
var velocity = Vector2()

func _ready():
pass

func loadPlayer1(obj):
    player1 = obj

func _process(delta):
    if player1 != null:
        velocity = Vector2()
        var rot_dir = (player1.position - position).angle()
        rotation += rotSpeed*rot_dir * delta
        velocity = Vector2(0,0).rotated(rotation)
        move_and_slide(velocity)
pass

My Result is  : Enemy Tank (red) keep rotating

Does anyone know how do i fix this?

Thank you


texts: How can I make the player slide when he does a 180 degree turn?

texts:
I'm making a roller skating game and I would like to player to skid or stop moving skating when they try to move in the opposite direction of their current one. But I'm not sure how to go about this.

I tried computing the the dot product of the input of the current frame and the last and if the product was less than  or equal 0 that must mean the player did  a 180 and the player's velocity was stopped. But it did not work, the product was always greater than 0,


texts: Can ARToolKit be used for color detection?

texts:
I'm trying to make an app that will show an object from different sides, but the target will be too small for any real marker detection.

Think of a cube with one or two centimeter sides. The camera distance is not a problem but it has to be at least ten centimeters out or what I'm trying to do won't work.

I was wondering whether it was possible to color one side of the cube differently than others and make ARToolKit recognize the color to know which side it's looking at. Is this possible or just not in the range of things ARToolKit can do? If so, is there any kind of AR that can do this.


texts: Unity: Bypass Ctrl+S in a custom Editor Window

texts: Is there a way to bypass Ctrl + S for Windows or ⌘ + S for Apple default behaviour (save scene) in a custom editor window?


texts:
Is there any way to implement websocket server, which I can run inside Unity3d standalone linux instance? I gonna connect to it directly from webpage (pure javascript, not Unity3d WebGL). I've tried to look for existing websockets libraries for C#, but the reason they does not fit because Unity3d can execute only Mono libraries with .NET 3.5 (.NET 4.6 in newest Unity3d 2017.1 release).

I have HttpListener server running fine, however for Websockets it needs lots of specific logic. Who knows any solution for this?


texts: I have an OpenGL renderer which has a Scene member variable. The Scene object can contain N SceneObjects. I use these SceneObjects for storing the vertex position and any transforms. My question is, where should shaders be stored in this arrangement? I guess they need to be in a central location because multiple objects can use the same shader. But then each object needs access to the shader because it needs to set attributes into the shader. Does anyone have any advice?


texts: Space Ship Move Left and right side but its not stop (stable or like vibrate) in the corner

texts:
I made the game space shooter. In my space shooter its move left and right but not stop in the corner( Stable or vibrate). I don't know how it will be stopped.

Player Movement. cs

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
    public float speedMove = 3;
    public float bonusTime;
    private Rigidbody rb;
    private float _limit = 0;

    // 1 for right and -1 for left.
    private float _direction = 1;

    // You can call it as speed
    private float _speed = 0.01f;

    private bool toLeft = true;
    private bool toRight = true;

    public GameObject shield;
    public GUIText bonustimeText;

    private bool counting = true;
    private float counter;

    private Weapon[] addWeapons;

    public Sprite strongShip;
    public Sprite normalSprite;
    public Sprite shieldSprite;

    private SpriteRenderer sRender;
    private Weapon weaponScript;

    void Start () {

        counter = bonusTime;
        rb = GetComponent<Rigidbody>();

        sRender = GetComponent<SpriteRenderer> ();
        addWeapons = GetComponentsInChildren<Weapon> ();
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }

        weaponScript = GetComponent<Weapon>();
        weaponScript.enabled = true;
    }

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

        transform.position = Vector3.MoveTowards (transform.position, new Vector3 (transform.position.x + _direction, transform.position.y, transform.position.z), _speed);

        if (Input.GetMouseButtonDown (0))
            _direction *= -1;
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "StrongMode") {
            Destroy (coll.gameObject);
            counting = true;
            StrongMode();
            Invoke ("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "ShieldMode") {
            Destroy (coll.gameObject);
            counting = true;
            ShieldMode();
            Invoke("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "Life") {
            GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
            gui.AddHealth();
            SendMessage("AddHp");
            SoundHelper.instanceSound.PickUpSound();
            Destroy(coll.gameObject);
        }

        if (coll.gameObject.tag == "Enemy") {
            SendMessage("Dead");
        }
    }

    void Downgrade()
    {
        SoundHelper.instanceSound.BonusDownSound ();
        counting = false;
        bonustimeText.text = "";
        counter = bonusTime;

        sRender.sprite = normalSprite;
        weaponScript.enabled = true;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }
        weaponScript.enabled = true;
        shield.SetActive (false);
    }

    void StrongMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = strongShip;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = true;
        }
        weaponScript.enabled = false;
    }

    void ShieldMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = shieldSprite;
        shield.SetActive (true);
    }

//  void OnDestroy()
//  {
//      bonustimeText.text = "";
//  }
}


texts: What is Windows' software rendering API?

texts:
We usually use OpenGL or DirectX to work with the GPU. If I want to use the CPU to render 2D/3D graphics, how does it work and what API can I use for it on Windows?

I know there is no benefit in using the CPU for graphics when GPUs exist, but I'd still like to understand how it works.


texts: How can you tell if you are a large player on a large map or a small player on a small map?

texts:
If everything is scaled by a constant factor, can you tell that the world is smaller or larger?

I think you could look down at the ground and see that it's "closer".
But how do you know what should be the correct distance? What visual clues give it away?

Edit: The player controller has an FPS camera!


texts: AStar for isometric game with overlapping walkable areas

texts:
We're developing an isometric game that so far has had a single ground level (y = 0) for the avatar to walk on. Pathfinding for this can be solved with a relatively simple 2D AStar tile map.

We're now looking to add objects in the world that can elevate the avatar. There will be overlapping walkable areas, thus creating a problem of pathfinding in 3D space. These objects are distributed sparsely in the room, so I want to avoid keeping an entire 3D map of the room for a 3D AStar implementation. I've attached screenshots to illustrate.

What is the best way to accomplish this?


texts: player does not collide with walls unity 5

texts:
I just started a new proyect with a personalize first person controller, like arrow move style, it worked, but when I tryed to collide it with walls it did not happen, I tryed adding a capsule, then adding the camera, rigidbody, character controller and my script to that capsule , then if you can see there are two walls one with box collider trigger the other one unchecked, it walks around but it does not collide at all, i'll add my controller script + scereenshot, thanks for you time

#pragma strict

public var speed = 100.5;

function Update () {
//rotate
var horizontalDir = parseFloat(Input.GetAxis("Horizontal") * speed * Time.deltaTime);
transform.Rotate(0, horizontalDir, 0);

//move backward and foreward
var verticalDir = parseFloat(Input.GetAxis("Vertical") * (speed / 10) * Time.deltaTime);
transform.Translate(0,0, verticalDir);
}


texts: Why is Vector3.MoveTowards only working on a single frame?

texts:
I have three laptops in my scene and I am trying to bring them to front when I click on them. I am able to recognize which laptop is clicked by using the code below, but it doesn't move to the focus position in a single click: it moves only one frame so I have to keep clicking it.

void Update () {
        if (Input.GetMouseButtonDown (0)) {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

            if (Physics.Raycast (ray, out hit)) {
                if (hit.transform.name == "Laptop 1") {

                    Debug.Log("Laptop 1 is clicked");
                    Laptop1Trans.position = Vector3.MoveTowards (Laptop1Trans.position, FocusPointTrans.position, moveSpeed);

                } else if (hit.transform.name == "Laptop 2") {
                    Debug.Log("Laptop 2 is clicked");
                } else if (hit.transform.name == "Laptop 3") {
                    Debug.Log("Laptop 3 is clicked");
                } else {
                }
            }
        }
    }

I tried moving the move part to a method but still same behaviour.

Are there any workaround?


texts:
I'm currently trying to implement a physics gun for my game. What I want is for the entity to stay in the same position on the screen no matter how I wiggle the camera about, what is the correct way to achieve this?

I threw together a basic physics gun in 5 minutes (just to handle grabbing and moving the object) but it doesn't work as intended. The problem is obviously that I only handle changes in toolDirection (rotation) but largely ignore changes in toolPosition (translation). For reference, here is my current script (wrtten in Lua):

local toolPosition; --This always holds the position of the tool
local toolDirection; --This always holds a normalized vector indicating the direction the tool is pointing
local grabLocation; --This is the position in world space where the ray from the tool intersected the body of the entity

function UpdateTargetPosition()
    local relativeGrabDirection = (grabLocation - toolPosition).Normalize();                 --direction from tool to target grab point

    local axis = relativeGrabDirection.Cross(toolDirection);
    local angle = math.acos(relativeGrabDirection.Dot(toolDirection));
    local rotation = Quaternion.CreateFromAxisAngle(axis, angle);

    local transform = Matrix4x4.CreateTranslation(-toolPosition) * Matrix4x4.CreateFromQuaternion(rotation) * Matrix4x4.CreateTranslation(toolPosition);
    target.SetWorldTransform(target.GetWorldTransform() * transform);
    grabLocation = grabLocation.TransformByMatrix4x4(transform);
end


texts: I'm having trouble understanding how the uv map that Blender gives you works. It gives you a map with outlines which you should color in. But if I have a low-res texture I don't know where should I color in exactly. Should I place my textures between the outlines, or should my textures overlap the outlines?


texts: Deep copying or cloning in actionscript 3

texts:
I would like to make a mirror reflection of an entity in Flashpunk. So I would like to copy a spritemap from one Entity to another (reflectionEntity). If i use something like this

reflectionEntity.sprite = otherEntity.sprite;

reflectionEntity.sprite.scaleY=-1; // to reflect

then the graphic of the original entity is also scaled.

Is there a simple way out of this? I have been searching for the solution for more than an hour and have not found a suitable one.


texts: Ruby: implementing alpha-beta pruning for tic-tac-toe

texts:
So, alpha-beta pruning seems to be the most efficient algorithm out there aside from hard coding (for tic tac toe). However, I'm having problems converting the algorithm from the C++ example given in the link: http://www.webkinesia.com/games/gametree.php

Players are either 1 or 0, so doing 1 - player will switch the player

  WIN = 1
    LOSS = -1
    DRAW = 0
    INFINITY = 100
    def calculate_ai_next_move
        best_move = -1
        best_score = -INFINITY

        cur_player = COMPUTER
        self.remaining_moves.each do |move|
          self.make_move_with_index(move, cur_player)
          score = -self.alphabeta(-INFINITY,INFINITY, 1 - cur_player)
          self.undo_move(move)

          if score > best_score
            best_score = score
            best_move = move
          end
        end

        return best_move
    end

    def alphabeta(alpha, beta, player)
      best_score = -INFINITY
      if not self.has_available_moves?
        return WIN if self.has_this_player_won?(player) == player
        return LOSS if self.has_this_player_won?(1 - player) == 1 - player
      else
        self.remaining_moves.each do |move|
          break if alpha > beta

          self.make_move_with_index(move, player)
          move_score = -alphabeta(-alpha, -beta, 1 - player)
          self.undo_move(move)

          if move_score > alpha
            alpha = move_score
            next_move = move
          end
          best_score = alpha
        end
      end
      return best_score
    end

currently, the algorithm is playing terribly. It will initially pick the last space, and then choose the first (from left to right) available space after that.

Any idea with whats wrong with it?

Also, I've been doing TDD, so I know that self.has_this_player_won?, self.undo_move and self.remaining_moves is correct.


texts:
Earlier, I asked this question:
Landscape mode for game?

Where I had a directory for each and every layout, but the layout in the layout-land directory wasn't showing up when positioning my layout in landscape orientation.

So, someone suggested to me that it maybe that the

Layout-normal directories are overriding my regular layout-land directories. Is this true?
If so, will any other of my layout folders get overriding?** What is the purpose of layout-normal in the first place then anyway?


texts:
There are loads of questions (all of which I have looked at) on here about cameras following objects. Using them, I have successfully got my camera to follow my car when driving, but I am unable to make the camera swing right when the car turns left (so it stays directly behind it) and vice-versa.

So far, this is how I've got my camera following my object:

    camOrigin.x  = (0   +globalPos.x+velocity.x); //Camera Position
    camOrigin.y  = (0   +globalPos.y+velocity.y);
    camOrigin.z  = (100 +globalPos.z+velocity.z);
    camLookingAt.x = (0 +globalPos.x+velocity.x); //Camera Looking at Object
    camLookingAt.y = (0 +globalPos.y+velocity.y);
    camLookingAt.z = (0 +globalPos.z+velocity.z);
    camNormalXYZ.x = (0);                         //Camera Normal = Y
    camNormalXYZ.y = (1);
    camNormalXYZ.z = (0);

I have tried to use the same algebra I've used to calculate the cars direction and velocity because I figured the angle the camera moves would be the inverted angle the camera needs to move, but it didn't work.

    camOrigin.x  = (0   +globalPos.x+velocity.x-sin(rotX_rad)); //Camera Position
    camOrigin.y  = (0   +globalPos.y+velocity.y);
    camOrigin.z  = (100 +globalPos.z+velocity.z-cos(rotX_rad));

I'm unsure how to take this further.

Edit:
Little drawing to help describe the movement. I'm looking to move the camera from c to d when the car turns in the left direction (and vice-versa when turning right).

Update:

    rotX_rad = rotX*PI/180;     //convert to radians
    velocity.x = sin(rotX_rad); //calculate X coord
    velocity.z = cos(rotX_rad); //calculate Z coord

    //globalPos + velocity;
    globalPos.x + velocity.x*delta;
    globalPos.z + velocity.z*delta;

    ModelViewMatrix = glm::translate(viewMatrixMovingCube,globalPos);           //move/update car

    ModelViewMatrix = glm::translate(ModelViewMatrix,  glm::vec3(0,-48,0));     //position low on screen
    ModelViewMatrix = glm::rotate(ModelViewMatrix, rotX, glm::vec3(0,1,0));     //manually turn/control rotation of car


texts: How to find starting velocity for a body thrown by an angle when known distance it must pass?

texts:
From course of mechanic, we know, that to find distance, passed by a body thrown by an angle, we need to use that formula:

Sy(t) = V0 * sin(angle) * t - (gtt) / 2;
Sx(t) = V0 * cos(angle) * t;

My question is, how do we find the right starting velocity, if we know the distance body must pass (Sx and Sy) and angle (let's say, it's 45 degrees)?

I tried to derive formula, but it seems to be wrong:

V0 = ( Sy(t) + (g * t * t) / 2 ) / sin(angle_in_rads);


texts: How to get current Microphone Frequency in Godot

texts:
Let us say I want to create a singing game similar to SingStar, and for this purpose I want to get the audio pitch the microphone is getting, in real time, or as close as possible.
I know I can get audio input in Godot. Even record the microphone to a file, there is an official demo project that does that (mic_record). I also know there are libraries that can analyze the audio.
How can I get the microphone pitch in real time?

Yes, I'm answering my own question. This question is inspired on a similar one on StackOverflow, which asked for a library to do this, which lead to the question getting closed, and the asker deleted it instead of editing the question… Before I noticed. As it turns out, you don't need libraries to do this. This is a means to answer the question I believe that person should have asked.


texts:
Trying to get the example code for CalcEyeFromWindow() (first one on the page) to work in WebGL, but having no luck.

Paired down the code to the following with some explicit values just in case something is amiss with parameter passing.  Visualizing the output on a sphere of unit radius, centered in the view and 3 units from the camera.  Using step() in the output to provide sharp color transitions on the sphere.

The current output is black.  If I set the step to 0 for X and Y, the transitions for X and Y are centered on the sphere, so it would seem that the problem is at least in part due to the calculation of clipPos.w.

Vertex shader:

precision highp float;

attribute vec3 a_position;

uniform mat4 u_modelMatrix;
uniform mat4 u_viewMatrix;
uniform mat4 u_projectionMatrix;

void main()
{
    gl_Position = u_projectionMatrix * u_viewMatrix * u_modelMatrix * vec4(a_position, 1.0);
}

Fragment shader:

precision highp float;

uniform mat4 u_inverseProjectionMatrix;
uniform mat4 u_projectionMatrix;

vec3 CalcEyeFromWindow(void)
{
    vec3 ndcPos;
    // Hard code window-space position at gl_FragCoord
    // Hard code viewport dimensions
    ndcPos.xy = (2.0 * gl_FragCoord.xy) / vec2(1000, 500) - 1.;
    // Hard code clipping depths
    ndcPos.z = (2.0 * gl_FragCoord.z - 1. - 4.) / (4. - 1.);

    vec4 clipPos;
    clipPos.w = u_projectionMatrix[3][2] /
       (ndcPos.z - (u_projectionMatrix[2][2] / u_projectionMatrix[2][3]));
    clipPos.xyz = ndcPos * clipPos.w;

    return (u_inverseProjectionMatrix * clipPos).xyz;
}

void main() {
    // Step to clarify position
    gl_FragColor = vec4(step(vec3(.5, .5, 2.2), CalcEyeFromWindow() *
         vec3(1,1,-1)), 1.);
}


texts: How can I update the size of a button after adding it to a table?

texts:
I have a table that acts as the HUD for my game. It features a bar (as a text button) and label showing how much shields are left. So I initially add the shield bar to the table, with the cell set at a certain size to correspond to maximum width of the shield bar when shields are at 100%.

I then want to be able to change the width of the shield bar to show shields dropping but my code doesn't seem work. Is anyone able to tell me how I change the size of a button after having added it to a table and having added it to the stage?

// Add shield bar and label to table
table.add(enemyShieldBar).align(Align.right).colspan(2).expandX();
table.add(enemyshieldLabel);
table.add(fillerLabel).row();

// Attempt to update the label and button size
enemyshieldLabel.setText("new text ");
enemyShieldBar.setSize(5,5);


texts: Apply shading to Solid Sphere? OpenGL C++

texts:
To Apply shading to an object. Let's say earth (which was textured using an image). So how to apply smooth shading to that? What are the steps I need to write? Using which functions? Thank you.

Code

void drawScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, textureOfSun);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix(); // Push matrices

// Draw Sun

gluQuadricTexture(quadricSun,1);
gluSphere(quadricSun,2,20,20);
glPopMatrix();

//Draw Earth
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureOfEarth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

//Rotation around Sun

//Revolve of Earth

glPopMatrix();
gluQuadricTexture(quadricEarth,1);
gluSphere(quadricEarth,0.75,20,20);

glutSwapBuffers();
}

This is the rendering part,

void initRendering()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
quadricSun = gluNewQuadric();
quadricEarth = gluNewQuadric();

textureOfSun = LoadTexture(location1);
textureOfEarth = LoadTexture(location2); /* location1 and 2 says the locations of images */
}


texts: Why can't I load an image with a relative path in SDL2 on Linux?

texts:
When loading a texture in SDL2 the general procedure is this:

SDL_Texture* texture = IMG_LoadTexture(renderer, "resources/images/image.png);

However this doesn't work and I have to supply the WHOLE path to the specific image. The code that I have to use is:

SDL_Texture* texture = IMG_LoadTexture(renderer, "/home/user/programs/game/resources/images/image.png);

This issue doesn't occur in a Windows Mingw32 environment.

Any suggestion on how to fix this issue?


texts:
I'm wanting to release a free version of an app to which I've already made a paid version.

I simply copied the project to another folder:

The project is initially the same as the paid application when finalized. I want to simply delete a few phases and put a link that takes the application paid in the Google Store (this I know how to do);

Turns out there is something called a keystore.

I would like to know if only thing I have to do is create a file.keystore in the directory with different name, rename the Filename (before Password) and click the generate button (below Country).

OBS - Obviously I will make a backup copy of the paid version file.keystore.


texts: Unity 5 - Place objects in game to closest gameobject

texts:
I am making a puzzle game in unity3D 5 for school and one of the puzzles is this: The player (third person) can pick up certain objects (4 objects) and has to place them inside holes in a wall in a specific order for a door to open.

I have 4 empty gameobjects named as slot001, slot002, slot003 and slot004 at the right positions at the holes in the wall. When the player has an item held and a certain button is pressed I link the transform of the object to the transform of the empty gameobject.

The problem is that the objects transform has to link to the transform of the closest gameobject. So when you stand in front of the slot002 gameobject the objects transform should link to the transform of slot002. The same goes for slot 001, 003 and 004 ofcourse. I am not sure how to do this.

I put the 4 empty gameobjects (slots) in a list.
I know of the Vector3.Distance() function and I tried using that to check for the closest distance with Mathf.Min() but I couldn't quite get it to work.

Any help or a nudge in the right direction would be appreciated!

Thanks.


texts:
I'm doing shadow mapping in my OpenGL 4.3 deferred renderer, and I'm starting with directional lights believing it to be the easiest.

What I do not understand is how the view projection matrix is to be constructed for the shadow mapping depth pass. I mean, all I have is the lights direction, and it affects the entire scene - so how do I construct the view matrix from only the direction, and what of the projection matrix?

Thanks


texts: What would be an easy extensible technique to store game data?

texts:
I'm looking for a technique for storing my game resources - levels, object (effects,world info), items (price,effects,...), NPC (visual info, behavior), everything except graphics/audio stuff. I've seen lua used for Awesome WM configuration. protobuf looks good, but it seems to be designed for network communication. I've tried to write my own parser, but as the project grows it's more and more harder to manage it and catch all the bugs.

My requiremets:

stability
easy extension of data without need to convert older versions to newer
not much coding
not XML!


texts: Path finding algorithm for (x,y) coordinates in c++

texts:
I am trying to code a path finding function in c++ . It should work like that, you supply the start point (x1,y1) and the end point(x2,y2) and it returns a list of points for the shortest path.

Assume that i want to go from the red tile to the blue one, however the grey tiles can not be walked on (like walls) .


texts: Some advice for settling on a map format for a tile game?

texts:
I am using XNA 4.0 and am currently working on a simple tile game to pass the time. Basically, I'm using the tried and true method of having numbers refer to tile types, where in 0 would be an empty tile, 1 would be grass, et cetera.

This is all well and good and works fine but I was wondering how to incorporate other assets. For example, a map may have parallax backgrounds, background music, and of course the tileset from which the tile map refers to draw its textures.

Ignoring ambient music and gratuitous scrolling backgrounds, I am still unsure of how to implement just the joining of the tile map (text) and tileset (png image). I see several solutions:

1) Embed the texture data for the tileset directly within the map file. This could be extended to other assets as well and would allow for all map files to be together in a single file. Unfortunately, the file sizes quickly become massive as raw texture data is several times larger than compressed images. For this I'm using GetData and WriteBase64.

2) Somehow mention the directory or filename of the tileset from within the text map file. This is how I typically see it done, but because I am using the content loader and not simply loading off the hard drive, this may not be possible. Perhaps the asset name could be stored but this solution seems a bit error-prone.

3) Completely separate the textual map data from the tileset image. At runtime, first load the map tiles and then allow any sort of tileset image to be loaded afterwards. This has the advantage of different map files using the same assets without duplicated data and very small file sizes. However, with this solution the width of the tileset would still have to be known before hand in order to correctly offset tile values. Also, map files may become lost and more easily edited by the user.

4) Create some sort of ZIP derivative in which all map files are contained in this package. Then, the textual map file can refer to the assets within this container. I'm not exactly sure whether or not this would work with XNA's content loader or how to implement it either, so I'm not sure of the this solution.

How do most developers typically solve this problem with XNA?


texts: Obtaining a certain type of object with component based design

texts:
I'm trying to design my game to be component based rather than overly hierarchical. Essentially, every high level object in the game (like gun, or whatever) inherits and implements the interfaces that it needs. For example, IPhysics, IRenderable, IWeapon, etc.

There are a few cases where I'm uncertain how to obtain a specific interface from another.

For example. A Gun might inherit from IWeapon, IPhysics, and IRenderable. I then also have a player which inherits from IPlayer, IPhysics, and IRenderable. I need a way so that, when Player and Gun collide, if Player is not currently wielding a weapon, he should be able to wield the gun and hold a pointer to the IWeapon of the Gun.

Right now, when Box2D detects a collision between 2 fixtures, I use the UserData field to store the IPhysics pointer associated with the fixture, and therefore, the IPhysics.beginContact method is invoked.

From here, the Player needs to somehow be able to know that this is a weapon, and obtain an IWeapon* . This is the part I really have no idea on.

Any advice on solving something like this is appreciated, even if it means some kind of design change on my part. I'm just looking for a clear way on how to solve this sort of problem.

Thanks


texts: Pathfinding with multiple random paths in a Tower Defense game

texts:
I thought about random pathfinding for my Tower Defense game. A* would not work for my puposes, because I specifically need random pathfinding.

Imagine a map with routes, a starting point and a destination. I have multiple routes, which all lead from the starting point to the destination, one way or another. It could look like this:

Color description: red - starting point; black - destination; grey - route; white - free space
(The numbers are used in the text as a reference to some tiles)

I first thought about just calculating the next waypoint randomly, when an entity passes a tile. But that would not work. When an entity passes tile 1 it either can go up or down. When it comes to 2 it can either go down/up (relative to it´s position) or right.
If it goes down/up it would go to tile 1, which means that it goes backwards. Bad...

I would really like to make it dynamic, but I can´t figure out what I can do now. Anyone with ideas or experience in this?


texts: Play animation state's clip from particular time or fram

texts:
I have a controller where i have a animation state. I want to play that animation clip from specified frame to specifed end frame. is this possible?

here is the snap shot of the controller

currently i am simply switching tow application using bool. I want to transition to paritcualr state but want to play its particular frame or time duration as a clip.

public Animator talkingAvatarAnimator;
    public bool isPlayHandGesture;

    void Update () {
        talkingAvatarAnimator.SetBool("isPlayHandGesture", isPlayHandGesture);

    }


texts: Level of Detail/Load on Demand for crowds: replace groups of objects instead of individual ones?

texts:
I have been thinking of using level of detail to make rendering crowds easier. The idea is to replace a group of meshes with a single one representing a group.

For example, you have 1 individual cube mesh. If you get 100 cubes together in a close space, replace all of those with a generic "blob of 100 cubes" mesh, that would be simplified and hopefully have a lower polycount than the sum of all 100 cubes. If 100 "blob of 100 cubes" meshes are together, then replace them with a simpler "blob of 10000 cubes" mesh. And so on.

There are many different challenges in doing this. Such as how to detect the objects are close? How to render the blob so it looks realistic enough? What to do about each object's metadata (physics, game variables)? etc So before I delve too much into it, I would like to see what is the current state of this technology and how people have been using this.

But I cannot find anything related to it. I've been looking for it for days, but every search I do about "LOD" and "crowds" only returns things about how to simplify each individual mesh of each game unit (ie. replacing a high poly count character, with a low poly character). Instead of replacing many game units with fewer ones, which is what I want to do. I've obviously played many games, and I can easily tell when they're using LoD for simplifying individual units. But I don't remember a single game that would replace groups. Am I looking it up wrong? Is there a specific term for this thing that I should be looking up for instead? Do you guys happen to know some case study examples of games that do this that I could check? Or maybe this isn't done at all?

Any help to point me in the right direction would be appreciated. Thanks.


texts: Unity3d change texture on terrain at specific vector3 at runtime

texts:
I need the terrain texture to change at certain positions depending on where trees etc. are randomly positioned at runtime. I'm struggling to find any solid information about how to take a particular vector3 and tell the terrain to paint a different texture of size x at that location. So far I have found a lot of information about how to change textures based on height map information. As my map is flat, that information doesn't seem very relevant.
EDIT: using the following code when each tree was randomly instantiated:
    public void ChangeTextureAtTreeLocation(Vector3 treePosition)
    {

        int mapX = (int)(((treePosition.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
        int mapZ = (int)(((treePosition.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);
        float[,,] splatmapData = terrainData.GetAlphamaps(1, 1, 4, 4);
        terrainData.SetAlphamaps( mapX, mapZ, splatmapData);
        terrain.Flush();
    }

got me this result:

As you can tell, the results aren't great. There are two main deficiencies:

I don't know how to access the terrain texture array directly so I paint a portion of the map first (see the bottom left of the image), sample that portion, and then set that sample at the location of the trees. This is not ideal as I cannot change the shape, size, or opacity of the added terrain texture. There is also no blending between textures, which gives the texture a rabbit burrow look.
you cannot see it in the image, but the textures do not appear under the trees but are directly north east of them. Not sure why that is. I'm assuming it has something to do with how textures are drawn relative to their origin.


texts:
I'm creating a 2D Game in Java. The world is tile based with a multidimensional Array and i have the architecture for the Server-Client system. The Users/Connections to the Clients are multithreaded and i have also created the packages.

Now my question is : Should my Client send a package to the server to request the current world state(with entites etc...) in his view range or should i create another thread in my connection/user class just for sending the world every servertick? Or is there even a better solution for sending/requesting the world with his enteties ?

The Game should have less latency and is real Time with an open World.


texts: How do I interpolate air drag with a variable time step?

texts:
So I have a little game which works with small steps, however those steps vary in time, so for example I sometimes have 10 Steps/second and then I have 20 Steps/second. This changes automatically depending on how many steps the user's computer can take. To avoid inaccurate positioning of the game's player object I use y=v0*dt+g*dt^2/2 to determine my objects y-position, where dt is the time since the last step, v0 is the velocity of my object in the beginning of my step and g is the gravity. To calculate the velocity in the end of a step I use v=v0+g*dt what also gives me correct results, independent of whether I use 2 steps with a dt of for example 20ms or one step with a dt of 40ms.

Now I would like to introduce air drag. For simplicity's sake I use a=k*v^2 where a is the air drag's acceleration (I am aware that it would usually result in a force, but since I assume 1kg for my object's mass the force is the same as the resulting acceleration), k is a constant (in this case I'm using 0.001) and v is the speed.

Now in an infinitely small time interval a is k multiplied by the velocity in this small time interval powered by 2. The problem is that v in the next time interval would depend on the drag of the last which again depends on the v of the last interval and so on... In other words: If I use a=k*v^2 I get different results for my position/velocity when I use 2 steps of 20ms than when I use one step of 40ms.

I used to have this problem for my position too, but adding +g*dt^2/2 to the formula for my position fixed the problem since it takes into account that the position depends on the velocity which changes slightly in every infinitely small time interval.

Does something like that exist for air drag too?
And no, I dont mean anything like Adding air drag to a golf ball trajectory equation or similar, for that kind of method only gives correct results when all my steps are the same.
(I hope you can understand my intermediate english, it's not my main language so I would like to say sorry for all the silly mistakes I might have made in my question)


texts:
I recently asked this question

        public void spawnCube() {
      cubes = new Array < Rectangle > ();
      for (int i = 0; i < 3; i++) {
          Rectangle cube = new Rectangle();
          cube.x = xpos;
          cube.y = ypos;
          cube.width = width;
          cube.height = height;
          xpos += 28;
          if (Gdx.input.justTouched()) {
              cubes2.add(cube);
              score++;
          }
          cubes.add(cube);
      }
  }

  public void moveCube() {
      Iterator < Rectangle > iter = cubes.iterator();
      while (iter.hasNext()) {
          Rectangle cube = iter.next();
          cube.x += speed * Gdx.graphics.getDeltaTime();
          if (cube.x + cube.width > 800 || cube.x < 0)
              speed = -speed;
      }
  }

The first method generates 3 cubes, the second one moves them from right to left and back. Cube size 15w 30h. Screen size 800w 400h.

The problem I have is that after 2 or 3 cycles of the cubes going from right to left, the cube on the left gets seperated from the other two. It seems that the other two cubes are pushing the first one out of place. How to prevent that from happening?


texts:
I figure that I intend to generate, for group orders, one optimal path, and then use a flocking algorithm to "glue" the units together as they all follow this one optimal path. However, a naive implementation would fail if, for example, the units were ordered from two distinct locations- two optimal paths would have to be computed. So for a group of units, I need to group them into subgroups which can all share the same optimal path.

At the moment, what I'm thinking is to pick an arbitrary unit in the group, and then pick all units in a certain, relatively small radius. Then for every unit in that radius, I increase the radius.

Are there any existing algorithms for grouping units into subgroups?


texts: I'm currently in the planning stages for an Web and iPhone game. I'm developing it with Adobe AS3/Air. I was wondering if it's possible for people to be able to play the Web version, save their state of play and then pickup again where they left of on the iPhone version? (and visa versa) how that would be achieved? the Web version will probably be on Facebook, so could I link both versions through their FB UID?


texts: How to take advantage of multiple core GPUs

texts: I'm interested in developing for the new Nexus 7 tablet when it finally arrives.  I've done a little OpenGL development for Android but I'm not sure what I have to do to take advantage of the 12-core GPU on the Nexus 7.  Does OpenGL take advantage of the cores for you (in some/all cases); if not, how do I specify which core does what, synchronize between them etc?


texts: How to set an EditorGUI foreground color for the light Unity skin?

texts:
Writing an asset management GUI as part of our editor tools, I am in some places colouring LabelFields. Working mostly in the dark Pro skin, this seems to work just fine:

GUI.color = Color.green;
EditorGUILayout.LabelField("Name", GUILayout.Width(75f));
GUI.color = Color.white;

When switching to the light default skin however, this colouring is no longer visible. The usual GUI.backgroundColor still functions fine there as it does in the dark skin.

Is this "foreground" colour something specific to the dark Pro skin? If so, is there perhaps another way to achieve a similar effect?


texts:
I want to add an easy and a hard level to this code:
#include<SFML/Graphics.hpp>
#include<iostream>
#include "menu.h"
using namespace std;
using namespace sf;

int pagenumber;

int main() {
    while(true)
    {
    RenderWindow window(sf::VideoMode(600, 600), "suduko");

    menu Menu(600, 600);
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
            if (event.type == sf::Event::KeyReleased) {
                if (event.key.code == sf::Keyboard::Up) {
                    Menu.moveUp();
                    break;
                }
                if (event.key.code == sf::Keyboard::Down) {
                    Menu.moveDown();
                    break;
                }

                //the num of the page
                if (event.key.code == sf::Keyboard::Return) //enter
                {
                    if (Menu.mainMenuPressed() == 0)
                    {
                        window.close();
                        pagenumber = 0;
                    }
                    if (Menu.mainMenuPressed() == 1)
                    {
                        window.close();
                        pagenumber = 1;

                    }

                    if (Menu.mainMenuPressed() == 2)
                    {
                        window.close();
                        pagenumber = 2;
                    }
                }
            }
            window.clear();
            Menu.draw(window);
            window.display();
        }

        if (pagenumber == 0)
        {
        //play

            sf::RenderWindow window_play(VideoMode(300, 300), "play", sf::Style::Close);
            while (window_play.isOpen())
            {
                sf::Event event;
                while (window_play.pollEvent(event))
                {
                    sf::Event event;
                    while (window_play.pollEvent(event))
                    {
                        if (event.type == sf::Event::Closed)
                            window_play.close();
                    }

                }

            }
        }

        if (pagenumber == 1)
        {

            //option

            sf::RenderWindow window_play(VideoMode(300, 300), "Options", sf::Style::Close);
            while (window_play.isOpen())
            {
                sf::Event event;
                while (window_play.pollEvent(event))
                {
                    sf::Event event;
                    while (window_play.pollEvent(event))
                    {
                        if (event.type == sf::Event::Closed)
                            window_play.close();
                    }

                }

            }
        }
        }

        if (pagenumber == 2)
        {

            //exit
            break;
        }

    }
    return 0;
}

Is there any kind of help ?


texts: Libgdx/Android/2D RPG game: optimizing time consuming when switching from Map to Map

texts:
I am completely new in game developing and even more new in the use of Libgdx. So far I have successfully done great thing on my game project thanks to all the advices I could have gathered on this forum. I would need your brilliant help once again.

- Context:

I have several TiledMaps and on each one of them, there is an object layer named “trigger”. This layer contains objects with name corresponding to an animation in my code.
All the animations of this layer are loaded thanks to TextureRegion.split.

- Issue:

When I load a new map or for instance a new floor in a house, the time spent to preload the animations of this new floor is too high. Here are the tests of the time spent to load 3 animations of 4 frames each and dimension 64x64 pixels (corresponding to 16 tiles):

0.7 sec on a Samsung Galaxy S6 (this is far too much for a powerful device and only 3 animations).
1.1 secs on a 4 years old Samsung Galaxy Note2.
2.2 secs on a 4 years old Sony Xperia M (pretty old and powerless though).

Here is the logic of my gamescreen class:

- Possible solutions:

1) Preload all the animations of the game in the OnCreate and loading screen:

Far from being a good idea with my current game architecture. I expect having 300+ animations (with the fighting ones, cutscenes…). With above tests, it would take 3+ minutes on a powerful device as the Samsung Galaxy S6 for instance.

2) Preload new map animations in another Thread when the user is approaching a teleport trigger:

It will be a good idea on device with good double core CPU but I am afraid of a big FPS drop on single core device or not good double core CPU (like double 600Mhz ones).

3) Label a group of animations with a level-flag and preload them only if level flag changes:

For instance: Level1 flag for 2 exteriors which contains 10 interiors (houses for example)

Level2 flag for 1 exterior and 6 interiors.

On that example, it will just require to preload and having a loading screen when we change of level but with the current architecture of my game code, it will still be a lot of time consuming.

If there is 20 animations and 20 fights animation per level it will be still 40 animations which represent about 7-9 sec on Samsung Galaxy S6 without including sounds loading…

4) Refactor all my code and include logic I was not aware of.

I think it is the best option here. I heard of AsseManager for instance but I have no idea how it is working with Animation object.

Thank you all for your help in advance!


texts: Is there a way to start UI animation transition with code in unity?

texts: I have made an animation for a button in unity's UI prefab, but i want it to start only at certain times, when i command it with code. How can i do this?


texts: How to design programatically a game map like Risk?

texts:
I'm making a quiz-game based on map territories with a system similar to the Risk game (except there are no tanks but tickets).

The map isn't the world but a custom map that I designed and I'll finish in the future, I just made the logic links among territories.

There are 10 territories who represent 10 different matters. The game I'm developing is for Android (Java), but I'm writing a prototype of the map in C# with Visual Studio to see if the idea of the map is good.

Now, I'm not asking for C# code to use in my app, I'm asking for a programming strategy I should use to implement my map in Code.

I wrote the class Zone to define each territory. I also wrote the class GameMap which implements 10 different Zones.

In the game logic, it's expected that just as risk, to attack 1 territory, you must have one near it. How can I implement at best this concept, of near and far territories in a dynamic and not long-static way?

The final result of what I want would be: I decide which territory attack in order to my owned territories. How can I proceed being as much as dynamic as I can and not write really long and in-efficient code?

EDIT: I'm no more looking for C# help. I'm directly implementing the map in Java and Javascript in both Client and Server sides.


texts: How do I determine the forward/right direction when I have the "up" vector? - Unity

texts:
I am trying to fix a gameobject for e.g. a cube (which i am using as a sensor) on my character. I need the cube to rotate (with orientation control from the inspector - I have a public quaternion rotation variable set). I have identified 3 vertices using ray cast to fix my sensor onto the character. I already have determined the normal of these vertices which will be the "up" direction of the cube. I am wondering how I can determine the forward/right vector to use in the LookRotation() function. I need to basically be able to rotate the cube ON the character even as the character moves on animation. This is my code, and as of now there is no rotation happening. I'm sure I am missing something and would really appreciate help. I really hope this is enough explanation.

using System.Collections;

using System.Collections.Generic;
using UnityEngine;

public class orientation : MonoBehaviour
{
    // importing from Vertex Finder Script to use InterpolatedNormalInWorldSpace value

private VertexFinder script;
public Transform target;

// to edit orientation of sensor in Unity Inspector
public Quaternion rotation_edit;

// Start is called before the first frame update
void Start()
{
    script = GetComponent<VertexFinder>();
}

Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp)
{
Quaternion rotateZToUp = Quaternion.LookRotation(exactUp, -approximateForward);
Quaternion rotateYToZ = Quaternion.Euler(90f, 0f, 0f);

return rotateZToUp * rotateYToZ;
}

// Update is called once per frame
void Update()
{
    Vector3 relativePos = target.position - transform.position;

    // aligning axes of sensor to z axis and y axis respectively
    Quaternion rotation1 = TurretLookRotation(relativePos, script.interpolatedNormalInWorldSpace);

    // setting rotation of sensor to values entered in Inspector with respect to the above aligned axes
    transform.rotation = rotation1 * rotation_edit;

}

}


texts:
I'm using NGUI to setup my UI in Unity.

Attached to the MainCamera I do have a script to rotate the camera view by clicking and dragging.

It does handle mouse events using Input.GetMouseButton().

The problem is that if I click and drag when the mouse is over a NGUI element (Button, Panel, Slider, whatever), NGUI handles all the mouse events correctly, but they also go through the MainCamera, and the camera rotate.

I want to prevent that.

If I use for example the Unity GUI.Button(), the mouse events are not transfered to the MainCamera and the camera does not rotate.

I have to replicate that, but using NGUI.

I have searched on their support forum, but i couldn't find a solution.


texts: Tile map creation, problem with position of tiles

texts:
I am trying to create a basic tile map script to learn Unity and I am unable to understand why my tiles are spaced far apart and I can't seem to control their spacing.

Moreover, there seems to be a difference between tile map size and Unity sizes, how do I convert tile map size to Unity size?

My understanding of tile maps are limited but here is what I want to do. I want to be able to set tile size, amount of tiles displayed and the spacing between each tiles.

Image: http://puu.sh/in6XW/416f8971bc.png

 public static int TILE_WIDTH = 32;
 public static int TILE_HEIGHT = 32;

 public float tileSize = 0.1f;
 private Transform[,] tiles;

 void Start () {
     var w = 18; // width
     var h = 15;  // height
     tilePrefab.gameObject.GetComponent<SpriteRenderer>();
     tiles = new Transform[w,h];

     for (int y = 0; y < h; y++)
     {
         for (int x = 0; x < w; x++)
         {
             Transform tile = Instantiate(tilePrefab, new Vector3(x* tileSize,y * tileSize,0),Quaternion.identity)as Transform;
             tile.parent = transform;
             tiles[x,y] = tile;
         }
     }


texts:
[crossposted from stackoverflow]

In a game such as Warcraft 3 or Age of Empires, the ways that an AI opponent can move about the map seem almost limitless. The maps are huge and the position of other players is constantly changing.

How does the AI path-finding in games like these work? Standard graph-search methods (such as DFS, BFS or A*) seem impossible in such a setup.


texts: Why is my perspective layer is painted over ortho layer?

texts:
The entire game takes place in ortho with the exception of the background layer which is drawn on a perspective camera.

Everything seems to be working well except that the background is displaying over the orthographic layer. I've tried fidgeting with the layers, orders and depth of cameras but I'm coming up dry.

Take a look at the pics and you may see what I mean.


texts: How to create a texture2d from an array of pixels in DirectX11

texts:
I currently have a ray-casting camera that holds an array of pixel colors (XMFLOAT4 color) that is 1024x768.

I am trying to create a Texture2D in DirectX11 that is also 1024x768 and simply copy over the pixels to the texture. I then want to apply the texture to a fullscreen quad to essentially display what geometry my rays are intersecting with.

    D3D11_TEXTURE2D_DESC textureDesc = { 0 };
    textureDesc.Width = 1024;
    textureDesc.Height = 768;
    textureDesc.MipLevels = 1;
    textureDesc.ArraySize = 1;
    textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    textureDesc.SampleDesc.Count = 1;
    textureDesc.SampleDesc.Quality = 0;
    textureDesc.Usage = D3D11_USAGE_DEFAULT;

    ID3D11Texture2D* fullScreenTexture = nullptr;
    ThrowIfFailed(mGame->Direct3DDevice()->CreateTexture2D(&textureDesc, nullptr, &fullScreenTexture), "ID3D11Device::CreateTexture2D() failed.");

Assuming I have XMFLOAT4 pixels[1024][768]; //Filled in appropriately with colors.

I'm not sure where/how I would take my pixel data and apply it to the texture. Any help would be greatly appreciated.


texts: Unreal Engine 4 is now only free or open source as well?

texts: Recently Unreal Engine 4 become free with Royalty fees. What about the code? Is it opensource or no?


texts: What is the minimum content that a game design document should have?


texts:
Many 2D games have an intentional screen freeze (say, 75 milliseconds) when the player takes or deals damage. During this freeze, all physics and animation processing stops.

How can one implement a screen freeze in Godot?

If you want to suggest how to do this in Unity or another engine, that's fine too. It might help me to figure out how to do it in Godot.

My only idea is to have a boolean called is_screen_freeze along with some variables freeze_start_time and freeze_duration. In all my nodes' _process() and _physics_process()methods, I can just pass if is_screen_freeze is true. This seems like a rather inelegant way of going about a screen freeze, and I'm not even sure it would work since animations would probably keep playing. Is there a better way?


texts: Architecture to draw many different objects in OpenGL

texts:
I have some objects that I want to draw. I am not sure how I can create my architecture in a way where I can draw everything as fast as possible.

As example:

class MyObject
{
  float[] vertices;
  float[] colors;
  float[] textures;

  public MyObject()
  {
    //fill every buffer with data
  }

  public void Draw()
  {
    //set shader
    //set shader uniforms etc.

    //foreach buffer
    BindBuffer();
    VertexAttribPointer();

    DrawArrays();
  }
}

In this way, I can draw every object like myObject.Draw after it is constructed. The problem would be, that if I have 5000 objects, I have 5000 draw calls. I need to set the shader every time even if I loop over the 5000 objects because I don't know if they use the same shaders.

Another way:

class MyObject
{
  bool needsToBeChanged;

  public MyObject()
  {
    //set my edge points
    needsToBeChanged = true;
  }

  void ChangeMyObject() //e.g. I changed the height of my object
  {
    needsToBeChanged = true;
  }
}

class GLWindow
{
  float[] vertices;
  float[] colors;
  float[] textures;

  GameLoop()
  {
    foreach(MyObject myObj in allMyObjects)
    {
      if(myObj.needsToBeChanged)
      {
        //get objects points for drawing it and set the global buffers up

        myObj.needsToBeChanged = false;
      }
    }

    DrawArrays(); //draw only once (because every data is in the buffer)
  }
}

Only 1 draw call for everything. I guess this will be faster than first method. The problem on this code is the big buffer that contains everything. Let's imagine we have inherited from MyObject and want to draw objects in different shapes. Now the Loop gets more complicated. You may have to split it because you need another shader for example for text. Now you have 2 arrays... And with other changes the Loop becomes more and more complicated and harder to maintain.

What solutions (beside the both) are available for this kind of problem? Can I use the first way or is there a better way where I can reduce the draw calls? How is it solved in other applications?


texts: Performance of 8 bit / 16 bit games vs Android/iOS games!

texts:
CONTEXT

I have always been intrigued by video games - NES and SNES in particular. Now I am a 32 years old computer professional who has mostly done his coding in Java and C#. I recently found great inclination for Android games and posting this question to much wiser community in the field for knowledge and awareness of everyone.

INTRO

NES brought an invasion of 8 bit games. Very sleek, very entertaining and surprisingly very compact in size - few hundred Kb only.
Games like Mario/Contra/Ninja/Zelda and countless more.

SNES followed the suite and brought an era of much graphically appealing games in 16 bit - still the size of the games were very compact and games were very powerful.

For Android, I have been doing some research for some good game engine and found that LibGDX is very powerful, open source and written for Java developers. A plus for any Android game developer.

THE QUESTIONS

What I am not able to understand is that how those classic game developers managed to put all those endless levels and game characters and features and goodies in just few hundred kbs!
I am trying to replicate just 1 level of Mario and the size is already reaching to 300Kb, let alone adding the files code and characters sprite images!
Can we implement similar principles of compact and powerful coding using Android and LibGDX? If yes, how - If no, why not!
Is it possible to create a game in 8bit/16bit code and then migrate it to the Android/iOS platform?


texts: How does the use of marching square and wave function collapse differ in a auto tiling?

texts:
I am discovering the techniques of procedural generation.
I struggle understanding on the usage of those two techniques:

Wave Function Collapse
Marching Squares

As I understand, both can be used to populate neighbourhood of a tile based on rules.

In the case of a game map editor where a user can "paint" a dungeon. When would you use one versus the other?


texts: Phong: Real-time rendering of Metal and Plastic Materials

texts:
Using a shader that works like Phong, what would be the difference between painted Metal and plastic?

I seem to remember reading in books that I no longer have access to, the following:

Specular color for painted metal is same color as the paint.
Specular color for plastic is always white.
Ambient for metal should be darker than for plastic.

This also seems to correlate with what I see when I observe objects (in real world)

But I tried to verify this also by checking the Internet, and found conflicting versions, some said the complete opposite.

So what is true?


texts: Word in different color in middle of string XNA

texts:
Is it possible to use different font colors for the same string, for example, when buying a weapon in CoD AW Exo Zombies:

How do I do this?

Thanks.


texts: How can I fix sprite vibrating randomly which is moving towards the mouse while using camera.position set to the sprite as the center?

texts:
So, when I use

camera.position.x = player.x;
camera.position.y = player.y;

to set the center of camera to my sprite, the code doesn't work as intended to. It's slightly hard to explain so i made this video(https://youtu.be/afCamx_wB_4) in which I show how it should work and the difference/problem when using camera.position

The code related to this is:

function setup() {
  createCanvas(displayWidth,displayHeight);
  level = new Level;
  player = createSprite(100,100,10,10);
  edge = createEdgeSprites();
  player.speed = 5;
}

function draw() {
  background(255);
  level.play();
  player.rotation = Math.atan2(mouseY-player.y, mouseX-player.x) * 180/PI;
  drawSprites();
}

player.collide(edge); //this part is from level.play()
var run = mouseX - player.x;
var rise = mouseY - player.y;
var length = sqrt((rise*rise) + (run*run));
var unitX = run / length;
var unitY = rise / length;
player.x += unitX * player.speed;
player.y += unitY * player.speed;

Also if you notice, when using camera.position, the vibration happens at specific distance of the sprite from the mouse, and the patter is that the distance is 0 right at the center of the canvas and keeps increasing as you move away from the center.


texts: Is there a material format for OpenCTM files?

texts:
I consider using OpenCTM files for my game. Since the format only claims to store raw mesh data, my question is if there is a associated file format for material data and paths to texture maps.

For example material of .obj meshes are stored in .mtl files. Is there such a format for OpenCTM, too?


texts: HTML5 multiplayer game - how to handle a variable interpolation?

texts:
To learn about online game development, I did a HTML5 real-time multiplayer game with NodeJS (server-side), like Agar.io/Slither.io.

Server and client updates 60 times/s, but server broadcast packets 20 times/s to save bandwidth.

Thus, client puts the packets in a buffer and renders them 100ms (constant lerpTime) in the past by interpolating. No prediction.

I've tested it on a small server and that's pretty smooth most of the time, but when the server does not keep the fixed rate, it stops (jittering) till the buffer is filled enough.

My questions are: how Agar.io and most of other smooth io games handle network congestion? Do they broadcast 60 times/s? How do they handle a variable interpolation time? Are just their servers powerful?

I've seen that they have a variable lerpTime (often < 100 ms, sometimes > 200ms) and a very smooth freezing (probably when lerpTime = lerpTimeMax).


texts:
Background

I'm currently working on a top-down 2D game, roughly similar to something like Zelda for the SNES.

Certain game entities such as the player or a typical enemy will consist of multiple collision boxes. For example:

The main collision box which determines collisions with the map (i.e. walls). It also determines where the entity can be hurt.
The attack collision box which, if overlapping a main collision box, causes the owner of that collision box to take damage.

The attack collision box should only be active when the entity is actually attacking.

One Solution

The first potential solution that comes to mind is the one used in fighting games where every frame of animation has its own set of collision boxes. This can obviously work, but it feels like it may be too over-engineered for what I need.

The Actual Question

Other than the solution above, is there a standard or common approach for attack collision boxes? Or is having collision boxes tied to animation the standard way of doing things?

I would like to emphasize the term "standard". It would be great to know how games like The Legend of Zelda, Secret of Mana, and Castlevania handle it.


texts: How can I de-rig & delete the skeleton while keeping the mesh?

texts:
There is this 3D model one can download here and  then import to 3DS Max with XNALara importer. (Side note: XNALara is also known as XnaPosingStudio)

Now this model already comes with a skeleton which is rigged. But if I want to rig the mesh to a different skeleton I need to delete the current skeleton correct?

When I have tried to delete the skeleton before the mesh got deleted with it.

So what I need to do is de-rig the skeleton from the mesh and then delete the skeleton, but how do I de-rig? Does anyone here know how? It's not a CAT rig.


texts: Low Res Atlas Texture vs. Many different materials without textures

texts:
So I have recently started to look into optimizing a medium complex 3D scene, more specifically i am looking to improve the performance i get from a fairly realistic bus. I am currently using the Unity3D standard shader. There are a lot of different objects within the scene, most of which are repeated and instanced. While many individual objects require only limited color variance often enough just a solid color and no texture at all.

I have read a lot about batching and atlasing but can't quite find an answer on the trade-off of using textures when no textures are required. I understand that reusing the same material allows for batching and can greatly reduce the amount of draw-calls, however how does this compare to the complexity of texture mapping if this could be avoided entirely? Is it still good practice to atlas solid colors on very low resolution atlas-textures and thus combine materials together? How does it look if i intend to use metallic and smoothness maps as well? Does it all come down to scene complexity and a number game or is there a straight answer?

I have the same uncertainty when it comes to objects which are made up of an arbitrary single digit number of solid colors; given supporting geometry, is it better to assign different materials with solid colors to regions of the object or create low-resolution textures?

In general; what is the point at which atlasing becomes the worse choice?

Thanks in advance!


texts: Unity Analytics: I see custom events in funnels, but not in the Event Manager?

texts:
I've just started using Unity Analytics, and I send two custom events: level1Started and level2Started.

After 1,5 days, the first results came in:

The funnels are working, so my custom events do reach Unity Analytics.
But in Event Manager I can't see the mentioned events by themselves.

4 days already have passed, the funnel is updated every day, but the Event Manager is still empty.

Or I'm looking at the wrong page? Then where can I see the raw number of events?

Why?

UPDATE:

For some reason, it took 12 days for them to show up in the Event Manager as well. Anyone knows why?

UPDATE AGAIN:

Now it's gone again. Why?


texts: UDK: Playing two audio tracks simultaneously

texts:
I have some environmental music playing in the background, but when I try to play another track (door opening sound effect) at the same time the background music stops playing.

How can I play two audio tracks simultaneously?


texts:
I'm using 1024 textures for smaller buildings and 2048 for larger one's. Basic workflow:

1) Unwrap in Blender

2) Smack a concrete texture on it

3) paint some dirt here and there.

Result:

This only works for small buildings. Here is an example from Battlefield 2, they put a small 128x128 brick texture and tiled it across the entire building and added Dirt on top of that.

Is there a way to do this using Unity or do I have to create my own custom shaders? (God forbid)


texts:
I am new to animations in android. I was wondering, is there a way to keep a button moving around the screen, bouncing off the walls, until it gets clicked? I was thinking to do something like this:

    while(!clicked){
    //Run code to move button
        }
  button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
    clicked = true;
        }
    );

And to make it random, do something like this:

Random r = new Random();
btnCount.animate().xBy(r.nextInt(10)+1).yBy(r.nextInt(10)+1);

But that doesn't work, and nothing happens. What is the best way to do this animation?

Thanks,

Ruchir


texts:
I have two components I'd like to connect them to each other.

PhysicalComponent
containing rigid body(position, rotation, velocity) and is holding body from physics engine.
GraphicsComponent
onscreen representation(position too, rotation too).

I'd like to sync this components, how to do it?

Read position, and rotation in GraphicsComonent from Physical comopnent.
Add one more component that sync them.

But problem is that I want to change on screen representation (other class such as PositionInerpolator do it, and it can work only with GraphicsComponent), and it must change physical body position. Is it a bad idea, and I must move physical body directly?

Thanks in advance.


texts: Debug Unity apps on Xbox One without ID@XBOX?

texts:
I have developer mode setup on my Xbox One, and can debug Windows Universal apps on it without issue from Visual Studio.

I am playing around with Unity, and would like to be able to debug on my Xbox one in the same way. When I look under Build Settings I see the following:

Clicking Open Download Page takes me to this blog post from 2014.

I have heard from other sources that I should be able to debug Unity games on the Xbox without an ID account, is this the case?

At this link, it says:

  You don't need help from ID@Xbox to begin experimenting with Dev Mode – just download the Dev Mode Activation app on your Xbox One to get started!

Cheers


texts: How can I implement sprite layering in a 2.5D game?

texts:
I started making a game, which has a 3D engine under it, but achieves a 2D look by using ab orthographic camera and billboards. Similar to how Don't starve, Realm of the Mad God and (I think) the new Stardew Valley manages entity rendering.

All three games I posted have structures in them (grass, trees, etc), and the player can go behind them. I want to achieve this effect. Of course, by having a fixed Z coordinate for the entities (I use Z sorting) isn't enough for this.

I once achieved this effect by making the entity's Z coordinate change based on their clip space position, but this I felt like this wasn't the best solution.

Basically, what's the best (fastest) way to achieve the above mentioned effect?


texts: Performance in pathfinding/road calculation

texts:
I have a question about the most effective way to detect road connection in a tile based world. Some time ago I already asked for "How to improve performance for expensive functions in 2d city builder" which was about building radius. Those hints were quite useful and worked great.
But now in this case I don't see I could use the same way as mentioned in that post. Let's start with my problem by a first image:

You can see 5 buildings on this little map. One on the left/the beginning of the map and four at the end of the long road on the right. All road tiles (separated in the black squares) are connected with each other.

Since I have to check if a building is still connected to the building on the left (which is the city entrance) it's needed to do regular road checks. To avoid doing expensive pathfinding stuff for each building I store the connection information in each road tile to have faster access. In the next image you can see those information. All road tiles have the same information since they are all connected to each other):

That works quite fast in smaller maps but if the map gets bigger, it's getting more expensive. My proceeding is the following: if a building is placed on a map it looks for surrounding roads. For these roads (could be up to 4 - for each direction) I check on and on if the next tile also has surrounding roads and so on. So finally I get an array of road tiles and update the road object information in all of them (whether building has been placed or removed). Do you know any optimization for this procedure already?

Since in a larger map I get an even bigger problem with the following situation:

Now I have a lot of objects on the right part of the map (this can be much, much bigger of course with hundreds of roads and buildings). If the player now disconnects the long road next to the building on the left, a lot of roads need to be updated.

Do you have any idea how I could improve handling this situation?


texts: Vertex with too many connections in Maya

texts: After some mesh editing in Maya I got one vertex with a lot of connections. Please help, how can I fix it? Don't even know how to google it.


texts: Getting the correct texture from an Atlas

texts:
I'm writing an OpenGL ES (2.0) app and have a custom Quad class which draws a textured quad for my sprites.

Currently, I put the textures of any sprites of the same size into a single file or atlas, then, when drawing, I can simply specify the frame I want. It will the render the correct frame based on how many textures in the atlas and how many total frames etc. Something like so:

mySprite.x = 0;
mySprite.y = 0;
mySprite frame = 1;
drawSprite(mySprite);

The texture Atlas would look something like this: (Simplified for the purpose of this question, in the real project, there are over 200 textures arranged in neat rows/columns, but the important thing is there is order, every texture is the same size as this is necessary for the calculations).

So, in the example above, I can say, there are 2 columns, 1 row and a total of 2 textures.

So, if I specify 1 as my texture (2nd texture), my sprite class can work out (using the columns, rows, total textures etc..) which texture I want and how to get it.  As I said this is simplified, the calculations are a little but more involved when there are multiple rows.  But it makes doing animations nice and simple as I can simply increment or decrement the current frame.

However, I keep seeing sprite sheets where there is no order.  There are different sized textures seemingly thrown into an atlas like so:

I really would like to go down this route as it means I wouldn't have to separate my sprite sheets by object size, and therefore, vastly reduce the number of separate sheets I have to use.

I can't however work out how one would write a calculation to get the correct texture just by specifying the texture number to render.

So how does this work?  Do I need to manually work out the texel coordinates of each and every object (and indeed frame), manually (and maybe store this value in an array and associate it to a frame number?) or am I missing a trick here somewhere?


texts:
I have an ai car script. The car needs to be able to slow down and or stop if it gets too close to another car. Right now I'm using 3 raycasts like so:

if (Physics.Raycast(lRay, out lHit, rs.forwardCollisionRayLength, rs.rayLayerMask) || Physics.Raycast(rRay, out rHit, rs.forwardCollisionRayLength, rs.rayLayerMask) || (Physics.Raycast(mRay, out mHit, rs.forwardCollisionRayLength, rs.rayLayerMask)))
{
    //some code...
}

However this is really long and inconvenient because it's a pain to figure out which raycast actually had the hit. And then there's other cases where multiple raycasts hit the same car, which point do I use, or if different raycasts hit different cars...Anyway, you can see that this is not ideal.

Also, depending on the size of an object, it could go between the raycasts. In the image below, the blue box is ok because its wider than the width between the raycasts, thus two of the raycasts find it. But on the other side, the green pole is too small, so the car can't see it and drives on.

I also need to get the distance between the hit.point and the car so that I know how much the car needs to slow down so that there's a reasonable distance between the two cars at all times.

I could use something like Physics.OverlapBox or Physics.CheckBox but then I can't get the distance between the closest point of the car, only the center of it. This is bad because some cars are longer than others - I need the distance between the nearest point of the car.

Also, keep performance in mind, I could solve the problem of objects going in between raycasts by adding more, but that will drain performance hugely, mainly because I have up to about 40 cars running at a time.

TL;DR: What are some alternatives for a raycast that can also give me the distance to the closest point?


texts: Android Game, Blurring effect while moving camera

texts:
I have posted this issue on stackoverflow, but unfortunately nobody couldn't find solution, maybe someone here know this.

I'm developing Side Scroll 2D Game, using AND ENGINE

http://i.imgur.com/j8oJD.png

I'm using their SVG extension (I'm using vector graphic)

But I discovered strange and ugly effect, while moving my player (while camera is chasing player exactly, means while camera is changing its position)

Images of my sprites looks just different, they are like blurred or there is effect like those images would be moving (not changing their possition, just jittery effect, really hard to explain and call this effect properly) Hopefully this image may explain it a bit:

http://i.stack.imgur.com/z02UL.jpg

Its more or less, how does it look in the game, where:

a) "FIRST" image is showing square, while player is moving (CAMERA isn't) image looks as it should

b) "SECOND" the same image, but with this strange effect "which looks like image moving/blurring during camera moving [chasing player])

Friend of mine told me that it might be hardware problem:

"the blurring that you notice is actually a hardware problem. Some phones "smooth" the content on the screen to give a nicer feel to applications. I don't know if it's the screen or the graphics processor, but it doesn't occur on my wife's Samsung Captivate. It happens on my Atrix and Xoom though. It's really noticable on the Xoom due to the large screen size."

But seems there is way to prevent it, since I have tested many similar games, where camera is chasing player, and I could not notice such effect.

Is there a way to turn this off in code?

I'm grateful for previous answers, unfortunately, still problem exist.

Till now, I have tried:

casting (int) on setCenter method which is being executed on updateChaseEntity
testing game using PNG images, instead of SVG extension and vector graphic
different TextureOptions
hardwareAcceleration

If someone have different idea, what may cause this strange effect, I would be really grateful for help - thank you.


texts: How should a one-man team do game audio?

texts:
Most game development (game design, art, programming, etc.) can be done by one person with relatively little equipment:
A game designer needs a pencil and paper, an artist Photoshop or Paint, a programmer a laptop and compiler.

Sound is different: External noises are a big problem, sound effects can't be made with instruments, and small mistakes easily produce disaster.

I can see how large companies with big studios and budgets do this.
How can I do this as a one-man indie?

Should I synthesize everything? Record sounds and buy some crazy program for editing them?


texts:
I'd decided to break the mold and make my first game based on RPG mechanics (note sarcasm).  An RPG style action bar would be a reasonable and fun way to get started as it's limited in scope but still challenging.

I have my spell bar and three targets.  I click a target, cast a spell, start the cast, put the spell on recovery cooldown, set the global cooldown, the spell goes through a casting phase then casts, the effect is applied to the target, mana is spent, the spell goes on cooldown or is removed depending.  Casting is animated, cooldowns are typical gray shading.  Then the other rules start to come into play.

When a spell is being the cast the target cannot be changed.
When a spell is on cool down we want a standard global cool down effect.
When a target has an effect we put a smaller version of the icon near
it which also has the same cooldown effect based on remaining
duration.
When the effect expires we need to remove it.
When something is on cooldown and another cooldown is triggered the
cooldown must become the longer of the two.
Each spell on a target has an effect such as damage or shield
Some effects, like shield, mitigate other effects, like damage

I've ended up with too many UI concerns checking the same pieces of data.  So my buttons have states, I tried the State Pattern, but ended up with the same type of crappy code in determining what state to set my objects to.

Take the example that a spell can't be cast if it's on cooldown.  Pretty straight forward as that's information the spell has about itself.  You can't cast if you have insufficient mana, getting more complicated because now I need to know about the state of the player to properly render the spell as shaded cause it's not available, can't cast on player if effect already exists, getting ugly now I need knowledge about the target and their effects as well.  Every one of these new situations resulted in my code bloating or getting stringy.

I'm event driven enough to detect clicks but should I go farther and be creating events for everything such as OnSpellCastBegin, OnSpellCastInProgress, OnSpellCastComplete, OnManaChanged, OnTargetChanged?

I would think it's the spell classes responsibility to answer if it can be cast but this requires it have a reference to the Player, and the PlayersTarget, and whatever else in the game in the future can effect a spell cast. What kind of design approach would support future adjustments to if a spell could be cast that followed the open/closed principal where I didn't have to modify the spell class every time?

thanks!