texts:
I have heard that textures consumes lot of memory but I am surprised how much....
I have 7 textures 1024 16 bit each. And while I will run my app it consumes 57MB of memory.
I think that this is "a bit" too much.

I am writing 2D application (no cocos or other framework)

Strange is that while I will compile my app with disabled rendering methods:
glDrawArrays than It uses only 27MB....  which is about 30MB less...

Do you have any Idea why?

I am creating textures before rendering of course:
rendering looks like this:

 [EAGLContext setCurrentContext:context];
 glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer);

 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

 glPushMatrix();
 glEnableClientState(GL_VERTEX_ARRAY);
 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
 glEnable(GL_TEXTURE_2D);

 glEnable(GL_BLEND);
 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

 TeksturaObrazek *obrazek_klaw =[[AppDirector sharedAppDirector] obrazek_klaw];
 glBindTexture(GL_TEXTURE_2D, [[obrazek_klaw image_texture] name] );

  glVertexPointer(2, GL_FLOAT, 0,vertex1);
  glTexCoordPointer(2, GL_FLOAT, 0, vertex2);
  glColor4f(1,1,1,alpha);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

 glDisable(GL_BLEND);
 glDisable(GL_TEXTURE_2D);
 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
 glPopMatrix();
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];

It looks like standard routine...
I have spent about 2 days looking for for answer and I still have no clue.


texts: How to move X and Y position of sprite in Game Maker Studio 2?

texts: In the tutorial it told me to add the sprite to the object and then add an event called step. The GML code i used in the step event is x = x + 4; to move to the right but when i run the game it does not move at all.


texts: LibGDX: Content appears stretched although I'm using a ScreenViewport

texts:
I just fixed another issue regarding the scaling inside a ScreenViewport. And yet another problem arises:

If I'm understanding the wiki correctly, a ScreenViewport does not scale or stretch the content in any way. In my case it somehow does:

When the game is started, it looks like this:

And after resizing the window (e.g. making it wider) it looks like this (obviously stretched...):

(The code is mostly still the same as in the linked question).

Since I couldn't find a example of using a ScreenViewport with unitScale yet, I have no idea how to make this work... Thanks in advance :)


texts: I am using .pngs for my textures and am using a virtual file system in a .zip file for my game project. This means my textures are compressed and decompressed twice. What are the solutions to this double compression problem? One solution I've heard about is to use .tgas for textures, but it seems ages ago, since I've heard that. Another solution is to implement decompression on the GPU and, since that is fast, forget about the overhead.


texts:
I'm trying to make a rolling ball game. But for some reason, I can't seem to get the counter to actually add to the score. Here's the code:

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

public class Movement : MonoBehaviour {
    public float speed;
    public Rigidbody rb;

    private int count;
    public Text countText;

    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody>();
        count = 0;
        SetCountText();
    }

    private void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * speed * Time.deltaTime);
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "item")
        {
            other.gameObject.SetActive(false);
            count = count + 1;
            SetCountText();
        }
    }

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

    }
}

It's super simple. Like, new new newbie simple. The objects I want to display as collected are tagged "items", they have colliders, and they are kinematic. I've followed the tutorial (this tutorial, specifically: https://www.instructables.com/id/How-to-make-a-simple-game-in-Unity-3D/) to the letter (barring some changes due to Unity updates), but for some reason it's not working.

I'm feeling a lot of anxiety cause I've had panic attacks about failure before and I really don't want to repeat it. Please help!


texts: Raycast returns miss even though it clearly hits its target collider, how to debug?

texts:
I'm trying to debug the following situation:

The raycast returns miss even though it clearly hits its target collider.
The target is a stock 3D Object Unity Cube.
The script firing the rays has a Public GameObject called 'target', the cube is correctly set as the target.
Here is the bulk of the raycasting I am doing. The rays are aimed at an array of positions within the bounds of the box called 'vertices'.
This was working yesterday and I didn't change the code and now it no longer works and I am completely stumped with no idea how to even begin to debug why.
    for (int i = 0; i < vertices.Length; i++)
    {
        Vector3 direction = vertices[i] - self.position;

        Ray ray = new Ray(self.position, direction);

        if (Physics.Raycast(ray, out raycastHit))
        {
            if (raycastHit.collider.transform == target)
            {
                Debug.DrawRay(self.position, direction, Color.green, 5.0f, true);
                hitCount += 1f;
            }
            else
            {
                Debug.DrawRay(self.position, direction, Color.red, 5.0f, true);
            }
        }
    }


texts: How can I output multiple sprite sheets from a single .fla?

texts:
I have to produce out three sprite sheets of differing sizes. To do so, I have three different .fla source files.

Obviously maintaining three files takes more time than maintaining one; is there some way that I can use one .fla and produce three differently-sized sprite sheets?


texts: I was watching a tutorial about Vectors in Unity, I understood the meaning of normalizing a vector but I wanna know why do we normalize a vector and if we don't what will happen ?


texts: Are there games with player programmable vehicle control behaviour?

texts:
My question

Are there any (space/flying/driving) games where the player can customize the mapping between player controls and the input to the vehicle actuators/engines programmatically? (Yes or no.)

                 ----------------                      ---------------
Player input -> | Control system | --Vehicle input--> | Vehicle model | -+-> Vehicle motion
                 ----------------                      ---------------   |
                        ^                                                |
                        |                                                |
                        +------------Feedback (optionally)---------------+

Basically games where the control system in the diagram above is replaceable by custom code.

Edit:

Just found out that Star Citizen plans to implement this to some extent. But my question is if there are any such games today?  (Yes or no.)

Why I'm asking

I'm curious to see what would happen if a game only imposed physical models of vehicles and let players choose how to adjust controls. I've been thinking about this on and off for some time, but never found it implemented.

For example, in spaceflight games the default could be a mode where say the roll is automatically stabilized, players could then modify this code to instead take full control over the thrusters, or just tune the aggressiveness of the stabilization down a notch. Since all ships have the same capabilities, this would allow a kind of individual modding posing no fairness problems in multiplayer.

I imagine some hardcore players would really like this, and it could be cool if players started sharing/trading settings to tune their ships. Maybe even making it possible to trade control systems as in-game items.

If sufficient signals where exposed through an external interface, it would even be possible to write complete autopilots in your language of choice. I would love to teach automatic control using a game. :)


texts: Libgdx box2d - what is the best approach to spawn an actor on a stage dynamically?

texts:
I'm currently building a 2d sprite infinite runner game, but everytime I spawn new enemy(actor) and platform, I noticed that there's a delay on it. Any idea of what would cause this behavior? I'm using textureAtlas to animate each enemy, and I used the same approach of Drops game in LibGdx.

Here's my code on the stage class

private void update(Body body) {
  if(TimeUtils.millis() - lastSpawnTime > 3000){
    float y = (float) (Math.random() * ( 5  - 1 ));
    setUpGroundInfinite(50 , y );
    createEnemy(51, y +  3);
  }
}

private void createEnemy(float positionX, float positionY) {
  Enemy enemy = new Enemy(WorldUtils.createEnemy(world,  positionX,  positionY));
  enemies.add(enemy);
  addActor(enemy);
  lastSpawnTime = TimeUtils.millis();
}

If you see any other way to optimize my game, I'd like to know them!


texts: Get MouseUp event outside of Sceneview scene window?

texts:
So I have an editor script that uses a dragging operation which works quite nicely.  Except, if you release the button while OUTSIDE the Scene Window, the event doesn't register.
How do I detect mouseup outside of the scene window?
private static void OnScene(SceneView sceneview)
{
    Event e = Event.current;
    if (e.type == EventType.MouseDrag)
    {
        //do some drag stuff
        e.Use();
    }

    if (e.type == EventType.MouseUp && e.button == 1)
    {
        //is the Right Mouse button released?
    }
}

I suspect somehow it's due to my Event e being inside the OnScene making the mouse actions only existing in the context of the Scene Window perhaps?  I have no idea, very new to Editor scripting...


texts: How do I render into a sub-region of a texture atlas with XNA / HLSL?

texts:
Is it possible to render into a texture atlas?

I've been wondering how to reduce the number of textures required for shadow-mapping, and came across a blog post here about rendering up to sixteen shadow maps into one texture-atlas.

According to the blog post mentioned above, these are the steps required:

1. The first step is writing to the texture; bind it to the framebuffer and set the viewport to render into the texture sub-region.

2. When accessing the sub-region, scale/bias the texture coordinates as follows: scale = region size / texture size, bias = region offset / texture size.

I understand this, but I'm not sure how to alter the viewport specifically to allow me to render into a certain square of the texture. I've found plenty of information about reading from it (up-sampling and down-sampling) but I don't know how I'd manipulate the viewport specifically to render into a small square region of the screen, and how I'd do this with a texture smaller than the back-buffer.

I'm using XNA and HLSL at the moment because it's simpler than SharpDX, and there's no point in messing around with that until I've got the theory working 100%.

Thanks for your help.


texts: Commonizing cycle time across different browsers for HTML5

texts:
Is there a good (accepted) method for "fixing" the cycle time within an HTML5 canvas game implementation?

The game that I have been working on runs far quicker in Google Chrome than in other browsers such as Firefox, Opera, or IE9.  To be honest, it kind of reminds me of running a game from the early 90's on a brand new machine.


texts: Why do these quaterion multiplications produce different results?

texts:
I am trying to use quaterions to modify the camera direction vector.

This code works perfectly:

glm::quat temp1 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.x  * mouse_sens * time_step), glm::vec3(0.0, 1.0, 0.0)) );
glm::quat temp2 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.y  * mouse_sens * time_step), dir_norm) );

Camera1.SetCameraDirection(temp2 * (temp1 * Camera1.GetCameraDirection() * glm::inverse(temp1)) * glm::inverse(temp2));

This code does not:

glm::quat temp1 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.x  * mouse_sens * time_step), glm::vec3(0.0, 1.0, 0.0)) );
glm::quat temp2 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.y  * mouse_sens * time_step), dir_norm) );

glm::quat temp3 = temp2 * temp1;
Camera1.SetCameraDirection(temp3 * Camera1.GetCameraDirection() * glm::inverse(temp3));

Why can I not multiply quaterions successfully?
Am I using GLM wrong?


texts: Customizable 3D "growing" Avatars within Unity

texts:
I'm working on a project that allows the user to pick their personal avatar (change faces/body settings/etc), and then have child/adult versions of those.  Ideally, they will allow an age progression from Age 3 - Age 100 (or something).

I've built an HTML5 page with something conceptually like what I want (github repo here), but obviously I'm looking for a system that works within Unity3D for fully animated avatars.

It seems that a possible solution is UMA2 (with the ingame avatar creator), but there's very little documentation and I can't find any "getting started guides online".  It also seems to have a DNA system that I could use for having parents have representative children, but can't find details.  There is a YouTube video series that I'm going through which seems quite good, but I haven't yet seen if there's anything to create children procedurally and how that would work.

Does anyone know whether the Unity team recommends this system or another one or what their roadmap is.  I see some UMA tools look like they're discontinued, some posts say they don't work with latest versions of unity, etc... but no ground-truth.

My current plan is to just buy a bunch of UMA stuff and slowly learn it through Trial and Error, but would appreciate if anyone has a good analysis of this area that they can share.

Note: I'm familiar with Makehuman and Adobe's Mixamo (both awesome and things I've spent a lot of time studying), but I am looking for something in-game to allow people to grow and evolve over time.  Bonus points if I can have 20 generations of marriages/children that show genetic traits passing down the line.  I've built support for that into the HTML5 system above, but not sure if it exists in the 3d space.

Thanks in advance!


texts: Polygonal Triangulation - algorithm with O(n log n) complexity

texts:
I wish to triangulate a polygon I only have the outline of (p0, p1, p2 ... pn) like described in this question: How do you triangulate an arbitrary polygon? and this webpage: http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Ian/algorithm2.html

I do not wish to learn the subject and have a deep understanding of it at the moment. I only want to see an effective algorithm that can be used out of the box. The one described in the site seems to be of somewhat high complexity O(n) for finding one ear. I heard this could be done in O(n log n) time. Is there any well known easy to use algorithm that I can translate port to use in my engine that runs with somewhat reasonable complexity?

The reason I need to triangulate is that I wish to feel out a 2d-outline and render it 3d. Much like we fill out a 2d-outline in paint. I could use sprites. This would not serve cause I am planning to play with the resulting model on the z-axis, giving it different heights in the different areas.

I would love to try the books that were mentioned, although I suspect that is not the answer most readers are hoping for when they read this Q & A format. Mostly I like to see a code snippet I can cut and paste with some modifications and start running.


texts: Initializing Variables, Difference between Awake and in-class initialization

texts:
public class ExampleClass: MonoBehaviour
{
   int exampleVariable = 0;
   int exampleVariableForAwake;
   void Awake()
   {
      exampleVariableForAwake = 0;
   }
}

What is the difference between initializing a variable at declaration vs. initilize in Awake?
Which I understand is to be used in place of constructors in Unity C#, welcome to correct me if I'm wrong.

Which usage is considered a proper convention by the community, if any?

Same question might also be in order for Properties, so I'll leave that open ended.


texts: Pygame Error AttributeError: 'pygame.Surface' object has no attribute 'add_internal'

texts:
I'm making my first game of Pygame. I'm going to create groups for making collisions but when I add an object to the group, I get an error in sprite.py (Pygame's Files)

AttributeError: 'pygame.Surface' object has no attribute 'add_internal'

Why I get this error?
There is a simplest way to make collisions?

There is my code:

import pygame
from pygame.locals import *
import sys
import os
import time
width = 950
height = 500
Game = False
GameOver = False
keyboard = pygame.key.get_pressed()[K_UP]
def main():
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption('Flappy Dog')
    background = pygame.image.load(os.path.join("Images", "Background_00.png")).convert()
    FlappyDog = pygame.image.load(os.path.join("Images", "Flappy.png")).convert_alpha()
    Play = pygame.image.load(os.path.join("Images", "Play.png")).convert_alpha()
    Dog0 = pygame.image.load(os.path.join("Images", "Dog0.png")).convert_alpha()
    Dog1 = pygame.image.load(os.path.join("Images", "Dog1.png")).convert_alpha()
    SpikeUp0 = pygame.image.load(os.path.join("Images", "SpikeUp0.png")).convert_alpha()
    SpikeUp1 = pygame.image.load(os.path.join("Images", "SpikeUp1.png")).convert_alpha()
    SpikeDown0 = pygame.image.load(os.path.join("Images", "SpikeDown0.png")).convert_alpha()
    SpikeDown1 = pygame.image.load(os.path.join("Images", "SpikeDown1.png")).convert_alpha()
    GameOver = pygame.image.load(os.path.join("Images", "Game-Over.png")).convert_alpha()
    Replay = pygame.image.load(os.path.join("Images", "Replay.png")).convert_alpha()
    Bone = pygame.image.load(os.path.join("Images", "Bone.png")).convert_alpha()

    Game = True
    Dog1_pos_x = 100
    Dog1_pos_y = 100
    screen.blit(background, (0, 0))
    screen.blit(FlappyDog, (0, 0))
    screen.blit(Bone, (550, 100))
    screen.blit(Play, (600, 350))
    screen.blit(Dog0, (5, 240))
    bones = pygame.sprite.Group()
    bones.add(Bone) # <-- Error here
    Dog = pygame.sprite.Group()
    Dog.add(Dog1)
    pygame.display.update()

    while True:
        if GameOver == true:
            screen.blit(background, (0, 0))
            screen.blit(GameOver, (20, 50))
        if pygame.sprite.gropucollide(Dog, Bones, True, True):
            Game = False
            GameOver = True
        while Game == True:
            pygame.event.pump()
            if pygame.key.get_pressed()[K_UP]:
                for i in range(10): # Up
                    Dog1_pos_y = Dog1_pos_y -1
                    screen.blit(background, (0, 0))
                    screen.blit(Dog1, (Dog1_pos_x, Dog1_pos_y))
                    screen.blit(SpikeDown0, (0, 436))
                    screen.blit(SpikeUp0, (0, 0))
                    pygame.display.update()
                    pygame.time.delay(1)
            else: # Down
                Dog1_pos_y = Dog1_pos_y +1
                screen.blit(background, (0, 0))
                screen.blit(Dog1, (Dog1_pos_x, Dog1_pos_y))
                screen.blit(SpikeDown0, (0, 436))
                screen.blit(SpikeUp0, (0, 0))
                pygame.display.update()
                pygame.time.delay(1)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                pygame.display.update()

if __name__ == "__main__":
    main()


texts: Couldnt visualize the mechanism describe by the code

texts:
Was reading this article http://www.jgallant.com/2d-liquid-simulator-with-cellular-automaton-in-unity/ but couldn't understand the mechanism in "CalculateVerticalFlowValue". Is the remaining liquid represent the tile just above the tile "destination liquid"? Would appreciate if can provide simpler example to visualize the mechanism as I couldn't see the logic behind this code.
using UnityEngine;
using System.Collections.Generic;
public class Liquid {

// Max and min cell liquid values
float MaxValue = 1.0f;
float MinValue = 0.005f;

// Extra liquid a cell can store than the cell above it
float MaxCompression = 0.25f;

// Lowest and highest amount of liquids allowed to flow per iteration
float MinFlow = 0.005f;
float MaxFlow = 4f;

// Adjusts flow speed (0.0f - 1.0f)
float FlowSpeed = 1f;

// Keep track of modifications to cell liquid values
float[,] Diffs;

public void Initialize(Cell[,] cells) {
    Diffs = new float[cells.GetLength (0), cells.GetLength (1)];
}

// Calculate how much liquid should flow to destination with pressure
float CalculateVerticalFlowValue(float remainingLiquid, Cell destination)
{
    float sum = remainingLiquid + destination.Liquid;
    float value = 0;

    if (sum <= MaxValue) {
        value = MaxValue;
    } else if (sum < 2 * MaxValue + MaxCompression) {
        value = (MaxValue * MaxValue + sum * MaxCompression) / (MaxValue + MaxCompression);
    } else {
        value = (sum + MaxCompression) / 2f;
    }

    return value;
}


texts:
I want to generate a mesh for the entire road network(later I'll probably want to split it into chunks but for now this will do).

My road network is stored as a TArray of pointers to a struct that contains the node location and pointers to each connected road(it's up to 4 nodes, each one has a direction).

struct FRoadNode
{
    int radius;
    float angle;
    TWeakPtr<FRoadNode> topNode;
    TWeakPtr<FRoadNode> bottomNode;
    TWeakPtr<FRoadNode> rightNode;
    TWeakPtr<FRoadNode> leftNode;
}

The road is following a polar grid. (see Frostpunk for example, it's almost exactly like that)

Each arc will be divided by its length to have as little vers as possible while keeping a nice curve.
If 2 line segments get too close the will be merged at the intersection point. (3rd example below, still not sure about this one...)
If 2 intersections are too close together they will be merged.

Here's the general idea of how I was thinking of generating the mesh:

I'm pretty new to generating mesh programmatically and to UE C++... so..
1. Is there a nice algorithm out there that will make my life a little bit easier?
2. How should I approach it?
3. Should I connect the road segment verts with the intersections verts?
4. Are there some advanced techniques that I need to know about?

BTW I saw somewhere a way to generate the road mesh by connecting all the nodes then extrude the edges, but I can't find it and I have no idea how this method called, If you know what I'm talking about, please tell what it's called\provide links.


texts: XNA - Autodeploy .exe of game upon succesfull commit to GIT

texts:
I know of ClickOnce which creates an .exe file so a user can play my XNA game.

However, I have to manually go through a wizard in order to create this file.

I would like for the new .exe to be created upon a successful commit of the code to GIT (ie. all my tests pass and the build succeeds) and for this file to be deployed on my Amazon AWS server so users can instantly download the 'new version' each commit.

Is this possible? I've been taking a look at Jenkins which seems to do what I want (Automated builds) but seems as though it's only for JAVA software.

Thanks for any info :)


texts:
We are doing a game in XNA that reacts to music. We need to do some offline processing of the music data and therefore we need a custom type containing the Song and some additional data:

// Project AudioGameLibrary
namespace AudioGameLibrary
{
    public class GameTrack
    {
        public Song Song;
        public string Extra;
    }
}

We've added a Content Pipeline extension:

// Project GameTrackProcessor
namespace GameTrackProcessor
{
    [ContentSerializerRuntimeType("AudioGameLibrary.GameTrack, AudioGameLibrary")]
    public class GameTrackContent
    {
        public SongContent SongContent;

        public string Extra;
    }

    [ContentProcessor(DisplayName = "GameTrack Processor")]
    public class GameTrackProcessor : ContentProcessor<AudioContent, GameTrackContent>
    {
        public GameTrackProcessor(){}

        public override GameTrackContent Process(AudioContent input, ContentProcessorContext context)
        {

            return new GameTrackContent()
            {
                SongContent = new SongProcessor().Process(input, context),
                Extra = "Some extra data" // Here we can do our processing on 'input'
            };
        }
    }
}

Both the Library and the Pipeline extension are added to the Game Solution and references are also added. When trying to use this extension to load "gametrack.mp3" we run into problems however:

// Project AudioGame
protected override void LoadContent()
{
    AudioGameLibrary.GameTrack gameTrack = Content.Load<AudioGameLibrary.GameTrack>("gametrack");

    MediaPlayer.Play(gameTrack.Song);
}

The error message:

  Error loading "gametrack". File contains Microsoft.Xna.Framework.Media.Song but trying to load as AudioGameLibrary.GameTrack.

AudioGame contains references to both AudioGameLibrary and GameTrackProcessor. Are we maybe missing other references?

EDIT

Selecting the correct content processor helped, it loads the audio file correctly. However, when I try to process some data, e.g:

public override GameTrackContent Process(AudioContent input, ContentProcessorContext context)
{
    int count = input.Data.Count; // With this commented out it works fine

    return new GameTrackContent()
    {
        SongContent = new SongProcessor().Process(input, context)
    };
}

It crashes with the following error:

Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\Maarten\Documents\Visual Studio 2010\Projects\AudioGame\DebugPipeline\bin\Debug\DebugPipeline.exe'.
Additional Information: A call to PInvoke function 'Microsoft.Xna.Framework.Content.Pipeline!Microsoft.Xna.Framework.Content.Pipeline.UnsafeNativeMethods+AudioHelper::OpenAudioFile' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

Information from logger right before crash:

  Using "BuildContent" task from assembly "Microsoft.Xna.Framework.Content.Pipel
ine, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553".
  Task "BuildContent"
    Building gametrack.mp3 -> bin\x86\Debug\Content\gametrack.xnb
    Rebuilding because asset is new
    Importing gametrack.mp3 with Microsoft.Xna.Framework.Content.Pipeline.Mp3Imp
orter

Im experiencing exactly this:
http://forums.create.msdn.com/forums/t/75996.aspx

EDIT2

The second problem was fixed by using SoundEffect instead of Song inside the GameTrack struct and using an uncompressed audio format (WAV). It turns out that accessing AudioContent.Data is not supported for compressed formats.


texts: Box2d java contact point reference changes after collision

texts:
I am trying to hold the contacts made during a collision in an array list. After I add n amount of contacts, when I try to retrieve them later on, they point to the last contact made in the world.

How can I save the contact that was there initially?

I am using Box2d and Libgdx with Java.

public void beginContact(Contact contact) {
    Fixture fa = contact.getFixtureA();
    Fixture fb = contact.getFixtureB();

    if (isFixtureCheckpoint(fa) || isFixtureCheckpoint(fb)) {
        checkpointContact.add(contact);
    }
}

and when I am trying to retrieve in the update method, any contact that i get back is from the last contact made in the world:

public void update(float delta) {
    Fixture fa;
    Fixture fb;

    if (checkpointContact.size > 0) {
        fa = checkpointContact.first().getFixtureA();
        fb = checkpointContact.first().getFixtureB();

        if (isAnyFixtureRearWheel(fa, fb)) {
            // <--- This returns true. Why?
        }

        if (isFixtureCheckpoint(fa)) {
            context.progressHandler.checkpointPassed(fa.getBody().getWorldCenter());
        }
        if (isFixtureCheckpoint(fb)) {
            context.progressHandler.checkpointPassed(fb.getBody().getWorldCenter());
        }
    }
}

The comparison functions are comparing to different unrelated classes:

/* Check if ANY fixture is a rear wheel */
private boolean isAnyFixtureRearWheel(Fixture fa, Fixture fb) {
    if (((fa.getUserData() instanceof VehicleRearWheel) || (fb.getUserData() instanceof VehicleRearWheel))) {
            return true;
    }
    return false;
}

/* Check if fixture is contacting the flag */
private boolean isFixtureCheckpoint(Fixture f) {
    return f.getUserData() instanceof ProgressHandler;
}

EDIT: Last time I checked Java was considered a pass by value language?


texts: from unity, how do I set up timer for c# httprequest?

texts:
so I'm trying to make a internet connection with c# using unity, and what I want to do is make the client to connect to the site, and load the data.

but there are cases there's lag, or weak connection, etc. that prevents you from getting connected, and I want the client to stop attempting to connect and just return connectionError or something like that after certain amount of time.

my code for this so far:

void HTTPRequest_TimeOut ( )
{

    string url = "serverAddress";

    HTTPRequest request = new HTTPRequest ( new Uri ( url ), (req, resp ) =>
        {
            switch ( req.State )
            {
                case HTTPRequestStates.Finished:
                    // utf-8 인코딩.
                    byte [] Bytes_For_Encoding = Encoding.UTF8.GetBytes ( resp.DataAsText );
                    string Encoded_String = Convert.ToBase64String ( Bytes_For_Encoding );

                    // utf-8 디코딩.
                    byte [] Decoded_Bytes = Convert.FromBase64String ( Encoded_String );
                    string Decoded_String = Encoding.UTF8.GetString ( Decoded_Bytes );

                    JsonData getdata = JsonMapper.ToObject ( Decoded_String );
                    DB_INPUT_test ( getdata, "items" );

                    break;

                case HTTPRequestStates.Error:
                    Debug.LogError ( "Request Finished with Error! " );
                    break;

                case HTTPRequestStates.Aborted:
                    Debug.LogWarning ( "Error : Request Aborted!" );
                    break;

                case HTTPRequestStates.ConnectionTimedOut:
                    Debug.LogError ( "Error : Connection Timed Out!" );
                    break;

                case HTTPRequestStates.TimedOut:
                    Debug.LogError ( "Error : Processing the request Timed Out!" );
                    break;
            }
        } );

    request.Timeout = TimeSpan.FromSeconds ( 100 );
    request.DisableCache = true;
    request.Send ( );
}

at first I thought just changing request.Timeout would do the trick, I guess not?

currently if the connection is not strong(making mobile game) it just kinda "hangs" there, waiting for anything to load up.


texts: Recommended list of games to develop at the beginning?

texts:
I am looking for simple games that I should develop to learn the basics of how different game mechanics work. I have read in many places that it is good to make Pong.

Is there a recommended list of basic games to try recreate when starting with game development?


texts: How can I compute delta time in a cross platform fashion in C++?

texts:
I need a way to get time for calculating the delta time.

I see that OpenGL and GLFW have methods for it, but unfortunately I can't use them since I need to make server software too.

What is the best way to get the time, without using OpenGL/GLFWs methods? Either in milliseconds or microseconds.

Note: Must be cross platform, preferably in the default c++ 11 library or a part of the boost library.


texts:
I tried to make two spheres with bounding sphere to detect collision so they stop when they collide. But it seems that im having a precision issue. They stey stuck together because of small decimal keeping it stuck. Is there a way around this? Since they are in a 3d space, adding or subtracting a little off seems impossible and expensive. How can I solve these precision issues?

 oldleftright = leftright, oldupdown = updown;

if(GetAsyncKeyState(VK_RIGHT))
    leftright += 0.0001;
if(GetAsyncKeyState(VK_LEFT))
    leftright -= 0.0001;
if(GetAsyncKeyState(VK_DOWN))
    updown -= 0.0001;
if(GetAsyncKeyState(VK_UP))
    updown += 0.0001;

collide = test.Intersect(test2);
if (collide)
{
    leftright = oldleftright;
    updown = oldupdown;
}
collide = false;


texts: Getting Display Name via Steam ID for Non-Friends

texts:
When using the Steamworks SDK (in C++), is there any way to get the display/persona name from the CSteamID object, even if we are not friends on Steam? Or is this possible for friends only?

In that case, when using a Steam leaderboard, how else should I display the nick names of the leaderboard entries in my game?


texts: libgdx(android) touchup triggers more than once?

texts:
I have a function I run inside the touchUp method but when I click with the mouse during emulation, it triggers my function multiple times. I don't think its an error with the called method itself because if I put the call in KeyUp then it triggers once as expected.

If it matters I am working in android studio.


texts: Direct3D shader compilation fails with constant buffers

texts:
I've been particularly annoyed by a 'bug' for a couple days involving D3DCompile and vertex shaders with constant buffers. I'm assuming the bug is my fault (missing flag or small nuance of the poorly documented API).

During my asset compile process I compile this vertex shader:

cbuffer Frame : register(b0) {
  float4x4 model_view_proj;
  float4x4 inv_model;
  float4x4 inv_view;
  float4x4 inv_projection;
};

struct VS_INPUT {
  float3 position  : POSITION;
  float2 tex_coord : TEXCOORD0;
  float3 normal    : NORMAL;
  float3 binormal  : BINORMAL;
};

struct VS_OUTPUT {
  float4 position  : POSITION;
  float2 tex_coord : TEXCOORD0;
};

VS_OUTPUT vs_main( VS_INPUT IN )
{
  VS_OUTPUT OUT;
  OUT.position = mul(IN.position, Frame.model_view_proj);
  OUT.tex_coord = IN.tex_coord;
  return OUT;
}

With this code:

const D3D_SHADER_MACRO defines[] = {
  { "VERTEX_SHADER", "1" },
  { "D3D11",         "1" },
  { NULL, NULL },
};

D3DCompile(
  src, src_len,
  path,
  &defines[0],
  &include,
  "vs_main",
  "vs_4_0",
  D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY |
  D3DCOMPILE_OPTIMIZATION_LEVEL0 |
  D3DCOMPILE_PACK_MATRIX_ROW_MAJOR, 0,
  &blob,
  &error_msg_blob
)

I have verified (by stepping through) that my ID3DInclude implementation works and all input data is correct. However, I receive a E_FAIL with an associated error message:

error X3004: undeclared identifier 'Frame'

What gives?


texts: Calculate the intersection depth between a rectangle and a right triangle

texts:
I'm working on a 2D platformer built in C#/XNA, and I'm having a lot of problems calculating the intersection depth between a standard rectangle (used for sprites) and a right triangle (used for sloping tiles).  Ideally, the rectangle will collide with the solid edges of the triangle, and its bottom-center point will collide with the sloped edge.

I've been fighting with this for a couple of days now, and I can't make sense of it.  So far, the method detects intersections (somewhat), but it reports wildly wrong depths.  How does one properly calculate the depth?  Is there something I'm missing?


texts:
So I know how timestepping works.

As I understand it if I wanted to move a character at the same speed in real-world time I need to simply multiply the movement of the character by DT on each frame.

So code without timestepping

forever
{
  player.position.x += 1
}

and with timestepping

forever
{
  player.position.x += 1 * dt
}

I have noticed that it is frustrating in some cases to do it like this.  Because lets say I had a specific distance in mind for the player to travel in the frame, without timestepping I only need to add that ammount, however with timestepping I need to find a different value that produces the same results when multiplying by a "normal" dt value.

I was wondering how I could approach the following.

I want to move the player forward one unit each frame as long as the fps is 60. So I am going to call a function with moveForward(1) every frame.  However if the fps is 30 I want the player not to move one unit but instead travel 0.5 units each frame but still call moveForward(1).  So basically if their is no lag it travels 1 unit each frame if their is lag it still travels at the same "real world" speed but in code travels less far each frame.

My question is.  How would one calculate it?  Perhaps you could fill in this skeleton function.

var targetDT = (1.0 / 60.0)
var currentDT = //**Value changes each frame to represent currenty delta time of frame**//
func moveForward(units: Int)
{
   var scalar = //**IDK what goes here something that considers the fps**//
   player.position.x += units * scalar;
}

This is probably very simple math I am just not figuring it out!

Also what is the relationship between dt and fps if we consider that the render loop and logic loop happen at the "same" time simultaniously?


texts:
I'm working on a game that uses Flash for the user interface. I'm running into an odd issue with the origin of a library movie clip. Here are the steps to reproduce:

Create a new MovieClip and construct a single rectangle with both a fill and a stroke.
Set position of rectangle to (0,0) and notice that the origin is at the center of the border stroke surrounding the rectangle.
Change position of rectangle accordingly so that the origin is truly the top left (so if the stroke surrounding the rectangle was set to 10, adjust the position of the rectangle to 5,5.
Enable 9 slice for movie clip so that when you scale the rectangle it doesn't scale or distort the stroke surrounding the rectangle.
Drag an instance of the movie clip to the stage and use the free transform tool to scale it to the width of the stage. It should visibly be as wide as the stage.
Run the flash file and verify that the width during execution is not as wide as it was in design view.

So in a nutshell it seems that when you use the free transform tool, it distorts the origin even though 9 slice is enabled and it shouldn't (I would think). I understand that Flash denotes the center of a stroke to be the starting point and not the edge, which is why I adjusted the origin accordingly while editing the movie clip.

What I really need here is pixel perfect positioning for vector based components. I should be able to drag and drop a library movieclip that provides a window with a fancy border around it and scale it to whatever size I need, and place it where I need it to be without any odd positioning problems.

Here are some screenshots of the problem:

( i.imgur.com/8WU2F.png ) is a shot of my window with 9 slice enabled. You can see that the origin is correct being the top left of the window graphic.

( i.imgur.com/ciK8l.png ) is a shot of my window after using free transform to scale it to the width of the stage. It's pretty much perfect in design view

( i.imgur.com/QFUiJ.png ) is a shot of the flash application running. Notice that the window is no longer the width of the stage? I don't get it. It makes it very difficult to position because in order to get this to look right while executing, I have to make the window wider than the stage in design mode.

Any help is greatly appreciated. I'm sure it's something silly. This is pretty much bread and butter stuff that's been around since the early days of flash.


texts:
I have two entities. One has a sword, one has a bow and arrow. When the bow entity is 100 units away, he needs to begin attacking. Likewise, when the sword entity is 10 units away, he needs to begin attacking.

My idea is to create an actual physical body for collision detection and a range body (or fixture?) for range detection. However, I don't want the range body to start pushing and affecting other entities. I simply want to detect when one entity's range body collides with another entity's physical body.

Is this the right thing to do and how can I do this with Box2D?


texts: LibGDX: How to detect remote button press for Android TV?

texts:
On Android TV, I need to be able to detect the remote control centre button to start the game.

I tried:

if (Gdx.input.justTouched() || Gdx.input.isKeyJustPressed(Input.Keys.SPACE) || Gdx.input.isKeyJustPressed(Input.Keys.DPAD_CENTER) ||
                Gdx.input.isKeyJustPressed(Input.Keys.ENTER) ||
                Gdx.input.isKeyJustPressed(Input.Keys.BUTTON_SELECT) ||
                Gdx.input.isKeyJustPressed(Input.Keys.BUTTON_START))  {
...}

All does not work. The only one that works is isKeyPressed(Input.Keys.DPAD_CENTER), but that will return more than one key pressed.


texts: Windows 8 C# Compile spritefonts for MonoGame without XNA

texts: Hello Stack Exchange community.  Recently, I've been attempting to in some way generate sprite-fonts into XNB files for use with MonoGame.  The issue is however, as you may be aware, XNA is very incompatible with Windows 8 without a very ridiculous amount of tweaking(even the installer its self has issues).  Is it in any way possible to generate XNB files from sprite-fonts to be used with MonoGame, or is MonoGame doomed on the ability to use fonts in a Windows 8 development environment?  Also keep in mind, it would 'appear' that the popular method of bitmap font loading also has compatibility issues with Windows 8.  If there is no way of doing this with sprite-fonts, can you suggest any alternative libraries for C# that would allow for similar functionality to MonoGame with the ability to draw font effectively on a Windows 8 system?  Any help is appreciated, thanks.  Keep in mind, I am developing for Windows Desktop, not Metro.


texts:
I am trying to smooth a camera I create in my game, but I can't seem to find a way to actually do this correctly.

What I have :

//Calculate the "current" Forward vector
var cameraForward =
    -Vector3.Cross(-Self.forward, target.up)
    .normalized.Cross(target.up).normalized;
//Rotate the camera on the Y axis of the current target,
// and X Axis based on delta.y and CurrentVerticalLook
cameraForward =
    Quaternion.AngleAxis(delta.y, ViewTarget.transform.up) *
    Quaternion.AngleAxis(CurrentVerticalLook, Self.right) * cameraForward;

var offset = cameraForward * CameraDistance;
var pos = LookAt + offset;
Self.Position = pos;
Self.transform.LookAt(ViewTarget.position)

So what I ahve tried :

I tried Lerping the Vector Position, I tried smoothing the delta.y based on the last N frames.

The Camera I need is something like this :

Rotate on the Around UP Axis of the target and Rotate on Right Axis of the Camera, Camera Up is always = to Target UP.

So this is sort of Orbital Camera, but I am having trouble finding the correct rotation/operations.
The way its set right works, but the camera movement is jaggy, but I can't seem to find a way to add Slerp in there without messing everything.

Thanks!

Edit :
<>


texts: Propel entities at some angle (depending on explosion's position)

texts:
I have a 2D platformer. There are multiple particles that are just 1x1 colored pixels. Let's assume there are 256 particles laid out as a 16x16 cube. Say I popped an explosion right in the middle. All of these particles should fly out all over the place.

My question is how would I calculate the angle at which they have to be propelled toward and find what the initial velocity vector right after the blast has to be set to. I already have gravity and friction so that they would be naturally attracted to the ground and slow down after they have traveled a good distance along the X axis.


texts:
I'm using Crafty.js and am trying to point a sprite towards the mouse pointer.

I have a function for getting the degree between two points and I'm pretty sure it works mathematically (I have it under unit tests). At least it responds that the degree between { 0,0} and {1,1} is 45, which seems right.

However, when I set the sprite rotation to the returned degree, it's just wrong all the time. If I manually set it to 90, 45, etc, it gets the right direction..

I have a jsfiddle that shows what I've done so far.

Any ideas?


texts:
In my game I have programmed Body and Limb classes. The Body is guaranteed to have an origin in the center of its sprite. The Body class has a List of children Limbs, each with their own offset. Every Limb has a Master value which references the parent Body, but it also has a Parent value which references the Limb it is a child of. However, Limbs do not have to have a parent, they can directly connect to the Body.

The Master, Parent, and Children values of the Limb class:

    //Body containing all limbs this limb is connected to and others.
    public Body Master
    { get; set; }

    //Parent limb, if null then limb directly connected to the body.
    public Limb Parent
    { get; set; }

    //Children limbs
    public List<Limb> Children
    { get; set; }

The Limb methods have if statements to handle these situations. In relation to the offsets and rotations of the Limbs around the Body (using transformation matrices) things seem to work fine. Now, the problem I'm having is when a Limb is attached to another Limb. The child Limb draws and behaves as if it is rotating around the Body instead of its parent Limb, and the parent Limb itself vanishes. Limbs without Children that are directly connected to the Master Body have no issues. Because of this sort of recursive hierarchy I believe the problem has to do with reference types but I may be mistaken. Here is some additional code:

Demonstration:

Here is the worldPosition() method which is used to acquire the Limb's position in world space. I suspect it may be the culprit. The Master.Position is already in world space:

    public Vector2 worldPosition()
    {
        if (Parent != null) return (LocalPosition += Parent.worldPosition());
        else return (LocalPosition += Master.Position);
    }

Finally here is the Update() method of the Limb class:
http://pastebin.com/5L5v5p6x

EDIT: Upon further analysis it appears that any changes I make to either Limb seem to affect the other Limb in one way or another even though they are both quite clearly different instances.

Here is the code to make the initial Body and first Limb:

        b = new Body()
        {
            Sprite = FileFactory.Textures["shoulders"],
            Position = new Vector2(this.Position.X, this.Position.Y),
        };

        Limb l = new Limb()
        {
            Sprite = FileFactory.Textures["left_arm"],
            Master = b,
            Offset = new Vector2(2, 13),
            Origin = new Vector2(0, Sprite.Height / 2),
            RotationalDifference = (float)(0.2 * Math.PI),
            RotateSpeed = 0.15f
        };

        b.Children.Add(l);
        b.Initialize();

And the code to add the child Limb to the first (Parent) Limb:

            Children.Add(
            new Limb()
            {
                Sprite = FileFactory.Textures["right_arm"],
                Master = this.Master,
                Parent = this,
                Offset = new Vector2(27, 0),
                Origin = new Vector2(0, Sprite.Height / 2),
                RotationalDifference = (float)(0.2 * Math.PI),
                RotateSpeed = 0.15f
            }
            );


texts: How to write properly shader with gradient based on vertex-color?

texts:
I took 4 squares with the outer corners painted in black, and the other ones in white. For some reason, they have a different gradient.

fixed4 frag (v2f i) : SV_Target
{
    fixed4 mainTex = tex2D(_MainTex, i.uv);
    fixed4 overTex = tex2D(_OverTex, i.uv3);
    fixed4 final = fixed4(lerp(mainTex.rgb, overTex.rgb, overTex.a) * i.color, 1.0);
    final = lerp(float4(0, 0, 0, 1.0), final, i.color.a); // shadows

    return final;
}

How can i make the same gradients as bottom-left and top-right?

In-game this is faces of blocks (like minecraft) and gradients - is smooth shadow/light. So I cannot change tris


texts:
I'd like to know how to draw an arrow to represent a vector position, length and direction.

The issue is that I can't quite find an easy way to know the location and rotation of the triangle representing the arrow head.

If it can help, I'm using OpenGL/OpenTK(wrapper for C#).


texts: IOS OpenGl transparency performance issue

texts:
I have built a game in Unity that uses OpenGL ES 1.1 for IOS. I have a nice constant frame rate of 30 until i place a semi transparent texture over the top on my entire scene. I expect the drop in frames is due to the blending overhead with sorting the frame buffer. On 4s and 3gs the frames stay at 30 but on the iPhone 4 the frame rate drops to 15-20. Probably due to the extra pixels in the retina compared to the 3gs and smaller cpu/gpu compared to the 4s.

I would like to know if there is anything i can do to try and increase the frame rate when a transparent texture is rendered on top of the entire scene.

Please not the the transparent texture overlay is a core part of the game and i can't disable anything else in the scene to speed things up. If its guaranteed to make a difference I guess I can switch to OpenGl ES 2.0 and write the shaders but i would prefer not to as i need to target older devices. I should add that the depth buffer is disabled and I'm blending using SrcAlpha One.

Any advice would be highly appreciated.

Cheers


texts: Creating a lookup table of datamaps in Harlowe/Twine

texts:
I'm attempting to procedurally-generate a list of linked Passages in Harlowe 3 and am running into that lovely wall of simplified programming that is presented to the developer.  The thing is that I just want to prototype a simple story without converting everything over to Sugarcube/Snowman.
What I am trying to do and am struggling with is figuring out how to generate an Array of Passages and link them together.  I am absolutely OK with creating temporary lookup tables to link things together, however I'm struggling with the syntax for it.
My current feeling is that something like this should work, but I can't wrap my head around the API reference for this kind of activity.  The following is a pseudo-code attempt at what I'm trying to accomplish ... it doesn't work straight up but is an amalgamation of what I've been trying.
(set: $rooms to (a:))
(set: $num_rooms to range(1,20))
(for: each _iter, $num_rooms)[
  (set: $rooms to $rooms + (a: (dm: "title", "Room " + _iter, "Description", "Room " + _iter + " Description"))))
]

(set: $lookup to (dm:))
(for: each $room, $rooms):
  (for: each $room2, $rooms)):
    (if: $room is not $room2):
      <!-- random chance that it links up, example here to set the 'left' passage -->
      (set: $lookup to $lookup + (dm: "Room1_Left", $room2))

Then later on, pull up:
[[Go left | $lookup->Room1_Left]]
The issue is that I am struggling with some of the syntax here.  The above code doesn't work for me and I'm struggling with coercing it into the 'ideal' format.
If this is completely infeasible then that is fine, but I'm fairly certain I can hack this in with the correct syntax.  (Future projects I'd switch over to Sugarcube, but I want to try and give this the old college try before I completely dump it and refactor).
Edit
I got frustrated and switched over to Sugarcube (and 15 minutes into reading documentation/examples I'm already beyond where I got with Harlowe).  HOWEVER I'm going to leave this question up for now as I can see it being exceedingly valid for non-programmers to extend their IF games.  If a good answer rolls along I'll try it out in my local project.


texts:
i have been struggling with this problem on and off for a few years now - making a seamless stereographic projection texture mapping on a sphere where the two halves of the sphere use the projection onto planes touching the poles as appropriate.

intuitively it seems possible provided that the right data is in the texture and i've taken many approaches, but i always get a nasty seam around the equator.

i've tried smearing the colours out along the path i imagine the interpolator would take to try and get between the distant texels, but this still leaves a seam (though it makes it less objectionable).

i thought it might be to do with mipmapping, but forcing the lod in a shader does nothing.

i've tried overriding the derivatives (although this isn't always possible) and that doesn't fix it either (and i wouldn't expect it to because forcing the lod didn't).

i figured i might be able to get around this by wasting lots of texture space and making a sort of tiling texture that contains flipped versions of the projection at the top and bottom so that the interpolation path passes through something sensible-ish...

i've also tried limiting the interpolation paths along the x-axis/u-axis in the texture, since it also naively seems like this should have the right colours for the interpolator to run over inbetween the two halves.

i've also tried the very simple thing of multiplying by 0.9999 to remove rounding errors, as well as clamping the samples onto the circles.

i should point out that the same problem occurs with any texture addressing mode (wrap, mirror, clamp) and even if i manually clamp the texture coordinates in the shader.

also that i have debugged the uvs by putting them out through the shader and there is only the expected sharp seam in them:

none of this stuff properly gets rid of the seam, and its exceptionally objectionable compared to the usual kinds of seams.

does anyone have any other ideas for how to approach this? i can't find anything online about this. perhaps my approach is too novel...

now i know i can cheat, expand the projection and blend between the two across the equator, but i'd really, really, like to not double the number of texture samplings i'm doing per pixel for this.

(also i can avoid the problem with a cylindrical mapping, but thats no fun at all :D)

thanks in advance.


texts: How i can do colisions with irregular hitboxes?

texts:
I'm developing my new platform engine and i don't know how to program collisions with slopes - I'm using hitboxes.
For the collisions of rectangles i use this:

if (player.rec(Position, level.scale).Intersects(t.rec(level.scale)))

but this doesn't work for sloped collisions or triangular hitboxes.
How can I do this?


texts: HLSL - GPU Performance Impacts of degenerate triangles

texts:
The background: After refactoring some code last night and realising I have had an issue that may of been impacting GPU performance.

My particle system uses the geometry shader to expand a single point into a billboard polygon.  In certain circumstances, I was feeding in a normal for the polygon which was parallel with a camera vector, causing the polygons to be degenerate.  I suspect that there maybe of been 1 calculation that may of been coming back as a NaN also.  The app is using Direct X 11.3.

My Question: In this case, is there a performance hit:

For degenerate polygons (where the points are co-linear)
Where possible floating point exceptions can occur (NaN).  Obviously the NaN seems to of not caused a fatal error.

The reason for this question is that I seem to of improved the frame rate performance by about 5% after finding and fixing this edge case (and it is an edge case that does happen).  I may have a bias in what I have observed, I just wanted to know if this is something other devs have encountered in the past.


texts: How can I keep straight alpha during rendering particles?

texts:
Rencently,I was trying to save textures of 3D particles so that I can reuse the in 2D rendering.Now I had some problem with alpha channel.Some artist told me I that my textures should have unpremultiplied alpha channel.When I try to get the rgb value back,I got strange result.Some area went lighter and even totally white.I mainly focus on additive and blend mode,that is:

ADDITIVE: srcAlpha  VS  1
BLEND:    srcAlpha  VS  1-srcAlpha

I tried a technique called premultiplied alpha.This technique just got you the right rgb value,its all you need on screen.As for alpha value,it worked well with BLEND mode,but not ADDITIVE mode.As you can see in parameters,BLEND mode always controlled its value within 1.While ADDITIVE mode cannot guarantee.
I want proper alpha,but it just got too big or too small consider to rgb.Now what can I do?Any help will be great thankful.
PS:If you don't understand what I am trying to do,there is a commercial software called "Particle Illusion".You can create various particles and then save the scene to texture,where you can choose to remove background of particles.
Now,I changed the title.For some software like maya or AE,what I want is called [straight alpha].


texts: Preventing a game object that has faded out from colliding with other game objects

texts:
I have the following cycle for fading sprites in and out

fade out (1 second) -> delay (2 seconds)-> fade in -> delay (2 seconds)

Please see my code below:

IEnumerator FadeTo(Material material, float targetOpacity, float duration) {

    Color color = material.color;
    float startOpacity = color.a;

    float t = 0;

    while(t < duration) {
        t += Time.deltaTime;
        float blend = Mathf.Clamp01(t / duration);

        color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);
        material.color = color;
        yield return null;
    }
}

IEnumerator EnemyCycle()
{

    while (isRepeating)
    {

        for (int j = 0; j < enemies.Length; j++) {

            var _myMaterial = enemies [j].GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeTo(_myMaterial, 0f, 1f));
            enemies [j].GetComponent<CircleCollider2D> ().enabled = false;
        }

        yield return new WaitForSeconds (2);

        for (int j = 0; j < enemies.Length; j++) {

            enemies [j].GetComponent<CircleCollider2D> ().enabled = true;
            var _myMaterial = enemies [j].GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeTo(_myMaterial, 1f, 1f));
        }

        yield return new WaitForSeconds (2);

    }
}

The above code cycle works when I am not disabling and enabling the colliders. i.e., without the following lines of code:

enemies [j].GetComponent<CircleCollider2D> ().enabled = false;
enemies [j].GetComponent<CircleCollider2D> ().enabled = true;

But when I place the two lines (as I've done in the above code), the enemy game objects don't follow the fade in and out cycle, mostly they don't even fade out.
I really need to be able to prevent the enemies from colliding with other game objects when I have faded them out during my fade in and out cycle. How can I solve this issue?


texts: How to move the object with same pace regardless their target distance?

texts:
so I tried to get those first and third ball to be able to move with same pace no matter how curvy their target path is, I tried to get the y position of the target that the ball is moving to, but I cannot figure out how to actually control the speed of the ball when the target y position is higher or lower than the ball y position, it seems that the ball will keep on speeding and not at the same pace with other ball as well.

Here is the code so far..

float yDistance = transform.position.y - targetWayPoint.transform.position.y;

    if(yDistance != 0)
    {
        speed = speed + 0.5f;
    }
    transform.position = Vector3.MoveTowards(transform.position, targetWayPoint.position,  speed*Time.deltaTime);

    if(transform.position == targetWayPoint.position)
    {
        currentWayPoint ++ ;
        targetWayPoint = wayPointList[currentWayPoint];
    }

Any ideas? Thanks alot!


texts: Why is my control scheme is not casual enough?

texts:
I am building a game like counter strike but 2dimensional and for android, it is already in beta phase. I have already share it with my friends and classmates to play it. Almost all of them said the controls are bad. Followings are the current controls:

tap on player: shoot
tap NOT on player: pathfind to touchposition
vertical drag on screen: rotate the camera left or right

The camera position and rotation will respect the player's position and rotation to help them aim before shooting. I am trying to build this game as casual as possible, so the player can only shoot, hide (stop moving/idle), and seek (move). Is there a better controls or gameplay than the current one? I am willing to cut features or change the whole gameplay.. Thanks in advance.


texts: Generate race track using freeform curves

texts:
I am trying to generate a race track in Vertex Shader(constraint) and only using B-Spline/Bezier/Hermite curves. My problem is that when i try to widen the obtained curve by translating another instance of it (lets say translate the x value), at certain turns, the road gets thinner.

As input, i can only have a certain number of control points/knots with which to generate a 2-degree closed(start point = end point) curve B-spline.
The closed curve (translated on Z) is shown in the picture attached. The camera is positioned right above it. Every vertex from the curve has Y = 0, seeing how the track is flat without any height(no perspective view).

Is there any possible way to keep the road's width on all its sections?


texts: Sprite changes colour when imported into Unity

texts:
I create some simple geometrical shapes in Inkscape, then export it to PNG and import into Unity.

Positive example:
I make a rectangle of colour hsva(0, 0, 32, 255), export it as a 32x32 PNG image and import to Unity. Then I put it into the scene. When I check its rendered colour with a probe tool it's perfectly correct: hsva(0, 0, 32, 255).

Negative (problematic) example:
I create a right triangle of colour hsva(0, 0, 32, 255), export it as a 32x32 PNG image. Effect: half of the image is transparent and the triangle edge is "anti-aliased", but the main triangle's area in the PNG file still conserves its original colour.

Then I import it into Unity and I put it into the same scene and check its rendered colour with a probe tool. It's actually hsva(299, 8, 33, 255) - very dark purple, but still distinguishable from the (0, 0, 32, 255).

What am I doing wrong? Why is the rendered colour of the sprite different?
How can I solve this problem?

Thanks in advance for your help  :)

PD

Adding my import settings, as requested in on of the comments (now I'm experimenting with larger images 512x512, but the effect is the same):


texts: Unity movie texture behaviour when hidden

texts:
I have a UI with a button and a panel. Clicking the button toggles the panel on and off :

GameObject.SetActive();

Now the panel element has a child which is a plane. This plane has the following components :

mesh renderer
videoPlay, a script I've written
an audio source

The videoPlay script basically applies the MovieTexture to the plane's material, sets the plane's audioSource to the movie's audio clip, and starts audio and video.

public MovieTexture movie;

void Start() {
    GetComponent<Renderer>().material.mainTexture = movie as MovieTexture;
    GetComponent<AudioSource>().clip = movie.audioClip;
    movie.Play();
    GetComponent<AudioSource>().Play();
}

Now when at runtime I click the button (which hides the panel which is the plane's parent element), the audio and video stop as the plane disappears - which is expected behaviour.

When I reopen the panel though, the sound restarts right away but as if it were catching up for the time it was hidden (so it starts really fast and then comes back to regular speed) ; and the video is just frozen for - empirically and approximately - the same time the panel was hidden.

I've tried in the script - in Update() - messing with

if (!transform.parent.gameObject.activeSelf && movie.isPlaying)
    {
        movie.Pause();
        GetComponent<AudioSource>().Pause();
    }

for example, (and the same with Play() when it shows back up) but it doesn't seem to change anything.


texts: Typing text animation (dialogue) libGDX or in general

texts: Can anyone think of an efficient way to animate the typing dialogue text as found in pokemon? I have a vague idea of using string.length, and having a new letter drawn every .2 seconds or so, but rather than using a timer event, i was wondering if there is a better way to do this. for example an animation, but i can't find anything like that in libGDX. Any ideas?


texts:
I'm not entirely sure this is the right place since all I see is coding questions, but I'll ask anyway in the hopes that someone can answer or point me in the right direction.
I've been developing a pencil/paper war strategy game for a while now and have run multiple tests with other players, but I've been having one major issue with the action system.
The game is turn-based and phase-based during the turns. Each turn has 7 phases and each unit has anywhere between 1 and 7 phases, depending on the unit itself. The phases are split up for the turn phase, so a unit with a movement phase can only move on the x; |x|2|x|4|x|6|x|.
I have a separation of attack phases and movement phases which can be two different things. For example, a vehicle has a movement rating of 6 but an attack of 4. This means it can move 6 times and attack only 4 times but only on it's designated rating.
Hopefully that's enough explanation... Anyway, I have had an issue when it comes to initiative. If two units have an attack on the exact same part of the phase and both deal enough damage to destroy each other... How could I determine who attacked who first? Should one unit be able to destroy the other, or should both just destroy each other?
The second part of that would be... If both units still have the same attack phase and unit 1 deals enough damage to destroy the other but unit 2 only deals a small amount... Who went first? Should there be a dice roll or coin toss to determine or can someone help think of a way to fix this?


texts: Where can I read about techniques used in NES-era games?

texts:
I enjoy reading about techniques used in NES-era games. Is there a blog or site that is pretty much dedicated to this topic?

For example, here is an article talking about Pac-Man, and another about the movement in The Legend of Zelda.


texts: How to do concept art without knowing how to draw?

texts: I want to do some art's of my upcoming game, but dont really know how to draw. Wich program can I use, or should I draw it on paper? Just give me tips on how to do it.


texts: How do open world games handle efficiently enemy respawn?

texts:
I'm currently working on a 2D open world game loaded in chunks, initially I thought It would be sufficient to spawn entities randomly in a specific "radius" close to the player, and periodically remove distant enemies.

Though appealing, this system is inefficient unless you keep in memory the chunks surrounding the chunk the player is in (if an enemy needs to spawn on a chunk which is currently not in memory, you have no way of knowing wether you can actually place it in a specific tile or not, since it may be occluded by a wall) which is why I'm currently spawning enemies as soon as chunks are loaded, but there's a problem..

A massive complication arises when enemies are spawned with specific criteria. Assume a little dungeon spawns inside a chunk, it needs 2 enemies and a chest with loot in-between them. When you're done with it, it shouldn't respawn unless an hour passed. You can't just spawn those enemies inside the structure as soon as it's close enough to the player, otherwise you could go back 'n fort, kill the enemies and keep looting the chest's content.

Time to make a cache right? Let's forget for a moment any complication related to how you could make it memory efficient, and analyze this particular scenario:

The player enters a chunk with said structure
Enemies and chests are then spawned
A cache marks this particular dungeon as "already spawned, check back in an hour"
Instead of getting closer to the dungeon, the player moves in the opposite direction, until the dungeon gets out of view and enemies are removed since they're now too distant
..few minutes later, the player goes back where the dungeon is, only to find an empty dungeon because the structure was marked as "already spawned" and wont spawn again unless an hour is passed.

I thought about caching all enemies that where present inside a chunk when it gets out of view and restoring them as soon as the chunk is visible again, yet again this requires caching every entity inside a chunk and keep the entry available for an hour, and periodically check if in that particular chunk an hour is passed and we can spawn again enemies

Doesn't look too bad, but if a player moves in a straight line in my game for an hour I would need to cache about 200 chunks before cache entries start expiring!

Is there a better solution? How do modern games handle enemies spawn? How do they get around these difficulties? I'm particularly interested in knowing how online games do it considering the crazy amount of memory (which should be shared between servers) such systems may require


texts: Is it possible to update constant buffers/textures/variables by name?

texts: When I was learning OpenGL (some old version), the way to update variables in shader was to find their index or whatever by name (string) and then use that index to actually update them. And I've seen it's also possible to update variables by name using ID3D10Effect interface (I don't know if there's any ID3D11Effect). But since I'm not using effect files, I'm wondering if it's still possible. Or should I just stick to manually indexing constant buffers/variables (register(b0)) in shader and then using these indices (slots) in C++ code?


texts: What resources are available for Mac OS game development?

texts:
Are there are any modern resources on how to develop games for Mac OS?  I suppose this would include objective c, cocoa and opengl 3+.

The book Beginning Mac OS X Game Development with Cocoa looks very promising but isn't out until early next year.


texts: Knowledge of a Language vs. Games in Portfolio

texts:
How important is the knowledge of a language versus the games that you have developed in your portfolio?

To be more specific. Personally, I dislike C++ for several reason(mainly due to it's complexity, and pointers, and I prefer D as my language of choice thus far. Due to this, I've written two games in D instead of C++ that are my personal projects. Am I wasting my time with D? Should I start using C++ again?

For reference, I have 6 months of experience in C++. It's the first language I learned. I have messed around with SDL/SFML and a bit of Direct3D with C++ as well.

Even though I like D, i'd rather not waste my time learning it, if it in no way will help me get a job in the gaming industry.


texts: Best practice for organizing/storing character/monster data in an RPG?

texts:
Synopsis: Attempting to build a cross-platform RPG app in Adobe Flash Builder and am trying to figure out the best class hierarchy and the best way to store the static data used to build each of the individual "hero" and "monster" types. My programming experience, particularly in AS3, is embarrassingly small.

My ultra-alpha method is to include a "_class" object in the constructor for each instance. The _class, in turn, is a static Object pulled from a class created specifically for that purpose, so things look something like this:

// Character.as
package
{
  public class Character extends Sprite
  {
    public var _strength:int;
    // etc.
    public function Character(_class:Object)
    {
      _strength = _class._strength;
      // etc.
    }
  }
}

// MonsterClasses.as
package
{
  public final class MonsterClasses extends Object
  {
    public static const Monster1:Object={
      _strength:50,
      // etc.
    }
    // etc.
  }
}

// Some other class in which characters/monsters are created.
// Create a new instance of Character
var myMonster = new Character(MonsterClasses.Monster1);

Another option I've toyed with is the idea of making each character class/monster type its own subclass of Character, but I'm not sure if it would be efficient or even make sense considering that these classes would only be used to store variables and would add no new methods. On the other hand, it would make creating instances as simple as var myMonster = new Monster1; and potentially cut down on the overhead of having to read a class containing the data for, at a conservative preliminary estimate, over 150 monsters just to fish out the one monster I want (assuming, and I really have no idea, that such a thing might cause any kind of slowdown in execution).

But long story short, I want a system that's both efficient at compile time and easy to work with during coding. Should I stick with what I've got or try a different method?

As a subquestion, I'm also assuming here that the best way to store data that will be bundled with the final game and not read externally is simply to declare everything in AS3. Seems to me that if I used, say, XML or JSON I'd have to use the associated AS3 classes and methods to pull in the data, parse it, and convert it to AS3 object(s) anyway, so it would be inefficient. Right?


texts:
Does anyone know of a (free or paid) solution that enables 3D path finding?  Basically something like:

CalculateRoute(input_geometry, start_pos, end_pos, variance)

I found a good paper on the topic, but I haven't found any solutions via Google or even searching sites like odesk, etc...

I know recast/detour is great for ground navigation, but I can't find anything that involves flying/3D space.

Any suggestions would be great to existing solutions.


texts:
Hi I am working on a PyBox2D game and it became quite complex and I need to learn about collisions, so I made this very simple script in order to learn collision setting more effectively, however I am completely stuck, I really do not know how to detect whether the collision occurred and how to use that information

I have been stuck on this topic for about a week now. I googled it, looking for tutorials but nothing helped (mostly because these tutorials were not written in python).

So... I would be more than grateful if you showed me on my script for example how to change color of the rectangle when it hits the ground (I am not showing you what I have already tried because there were various ways using e.g. memory locations and I want to make this example as simple as possible.

import pygame
import numpy as np
from Box2D.b2 import world, polygonShape, circleShape,edgeShape, staticBody, dynamicBody, kinematicBody, revoluteJoint, wheelJoint, contact
from Box2D import b2Vec2, b2FixtureDef,b2PolygonShape, b2CircleShape, b2Dot,b2EdgeShape, b2Contact,b2ContactFilter,b2Filter, b2ContactListener

pygame.init()

PPM = 15
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
pos_X = SCREEN_WIDTH/PPM/3
pos_Y = SCREEN_HEIGHT/PPM

Box_2_World = world(gravity = (0.0, -9.81), doSleep = True)

Rectangle = Box_2_World.CreateDynamicBody(position = (pos_X+5, pos_Y + 5),
                                    angle = np.pi/4,
                                    fixtures = b2FixtureDef(
                                        shape = b2PolygonShape(box= (5,5)),
                                        density = 1000,
                                        friction = 1000,
                                                            ))
Ground = Box_2_World.CreateStaticBody(position = [0,0],
                                    angle = 0,
                                    fixtures = b2FixtureDef(
                                        shape = b2PolygonShape(box= (50,1)),
                                        density = 1000,
                                        friction = 1000,
                                                            ))

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
colors = {dynamicBody: (133, 187, 101, 0),  staticBody: (15, 0, 89, 0)}
FPS = 24
TIME_STEP = 1.0 / FPS
running = True

def my_draw_polygon(polygon, body, fixture):
    vertices = [(body.transform * v) * PPM for v in polygon.vertices]
    vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices]
    pygame.draw.polygon(screen, colors[body.type], vertices)
polygonShape.draw = my_draw_polygon

while running:
    # Draw the world
    screen.fill((255, 255, 255, 255))

    for body in Box_2_World.bodies:
        for fixture in body.fixtures:
            fixture.shape.draw(body, fixture)

    # Simulate dynamic equation in each step
    TIME_STEP = 1.0 / FPS
    Box_2_World.Step(TIME_STEP, 10, 10)

        # Flip the screen and try to keep at the target FPS
    pygame.display.flip() # Update the full display Surface to the screen
    pygame.time.Clock().tick(FPS)

pygame.quit()

Thank you VERY much for any response. I cannot move forward in my game without this...

P.S. I have posted almost identical question on Stack Overflow because the answer is really important to me, I apologize for spamming

EDIT: I have found a link which solves exactly what I want to do, but it is written in C++ and I do not understand it :(
http://www.iforce2d.net/b2dtut/collision-callbacks


texts:
I'm trying to do collision detection (which I have working well) but now I want to use it for a little more.  I want to check special circumstances for the collision.  Right now I'm checking for containsKey like so:

someCell. ... .getTile().getProperties().containsKey("collision");

This works fine.  But now I want to use the VALUE of that key to determine what the character hit and continue accordingly.  If the value is null, just a normal hit.  But if the value is a sign, and the user chooses, it can be read.  Or if the value is a chest, if the user chooses to do so they can open it (but check that locked is indeed false first, or the user can unlock it).

The thing is, I've looked everywhere and can't find a way to check the value of the key.  And yes, I can just create a lot of keys but it would be easier to have one key that can carry many values and check and alter them based on user input or game circumstances.  I tried

theKey = someCell. ... .getTile().getProperties().containsKey("collision")[.value("someValue");];
theKey.value("someValue");

but neither worked.

So, my question to you is this: how can I access and later edit the value of a custom key created in tiled map editor (should have mentioned that earlier, huh)?

Any help would be appreciated.


texts: How should I implement the "Observer" pattern with respect to a game world?

texts:
I'm thinking of ways to implement the Observer pattern in a game I'm developing at the moment. I can have a Game World (local map) with Game Objects (player, NPCs, monsters etc...) inside of it. Other Game classes (like quest progression tracker for flagging triggers, location tracker for path finding, or maybe a new map need to be loaded into memory and rendered to show the new area the player just walked into) need to be notified when the player walks into a building, or fires a projectile. Also the input listener needs to be aware of when the user presses a key or clicks the mouse, and somehow transport that information to the rest of the game so that it can allow the appropriate actions to take place.

So I'm stuck at the implementation stage. I know I can use the Observer pattern, and possibly the State pattern as well. I know I'll need a Game World (Subject), Game Objects (Listeners), and Game Events (triggers the Game World to render the changes). However that could be the wrong way to go about it, any suggestions?

BTW, its a 2D JRPG tiling styled game, in the fashion of Zelda, Breadth of Fire, Pokémon, or the older Final Fantasies

Alright I've gone and done an implementation, but ran into a few minor issues, although it seems to be working properly.

public interface WorldListener {
    public void OnWorldEvent(WorldEvent e);
}

Above is the Observer that listens to the subject.

public class WorldEvent {
    final int WorldObjectMovedEvent = 1;
}

Above is the Event that triggers a notification.

public class World {

    static WorldListener listener;

    static void addWorldListener(WorldListener wl) {
        listener = wl;
    }

    static void WorldChanged() {
        listener.OnWorldEvent(new WorldEvent());
    }
}

Above is the subject that only stores one subscriber at the moment, I'll make it into a list once i write a class for another observer, right now, I only have one Observer. There is no need for a list at the moment.

public void OnWorldEvent(WorldEvent e) {
    System.out.println("Something has happened in the world");
}

static private void addWorldListener(WorldListener wl) {
    World.addWorldListener(wl);
}

The code above goes into the object that is currently acting as an observer, when an event is fired, it triggers the world's WorldChanged() method, which in turn fires the OnWorldEvent of any listener.

The problem I have ran into is that I can't move the WorldEvent, WorldListener, or World classes into a separate package under the moniker World.my.game because of the static reference. So I'm not sure I'm implementing it correctly. Also if there are any suggestions on making this better, or if I'm flat out doing it wrong let me know, as I haven't delved into design patterns yet and this is my first attempt.


texts:
Had an idea for a modification to a game, however the core functionality heavily involves UI, and the API for the mod is event based.

The player will have there own custom data object, so I know one option could be

onClickEvent {
if Player doing X task { player.doX}
if Player doing Y task { player.doY }
}

on ScrollEvent {
if Player doing X task { player.setXValue}
}

I have a feeling this is not the best approach, so my question is what is the best approach to an event driven UI?


texts: Resetting The object scale to it's original size!

texts:
I have this sprite renderer in unity. I have made so that it increases it's scale.
The Object is:

This object is a child of empty gameObject and I have resized the parent gameObject rather than this one and added the script to parent rather than this object. The code I have written is:

Scaler = transform.localScale;
Scaler.x += 3f;
transform.localScale = Scaler;
if(Scaler.x > MaximumPoint){
Scaler.x -= 3f;
transform.localScale = Scaler;
}

This code doesn't work because if the object decrease by 3f, it isn't greater than MaximumPoint anymore. So, this code stops.

Another Code , I have tried is:

void OnCollisionTrigger2D(Collision2D col){
if(col.gameObject.name == "Collider"){
Scaler --;
}
}

This one throws a null pointer exception because I am not sure why?

Another thing I have tried is raycasting but the ray doesn't move with the increased scaled object.


texts:
I have the problem with seams with calculating a tangent basis in my application.
I'm using a seems to be right algorithm, but it gives wrong result on the seams. What am I doing wrong? Is there a problem with an algorithm, or with the model? The designer says that our models with our normal maps are rendered correctly in Xoliul Shader Plugin in 3Ds Max, so there should be a way to calculate correct tangent basis programmatically.

Here's an example of the problem I'm talking about.

 Steps, I've already taken:
- Tried different algorithm (from Gamasutra, I can't post the link because I don't have enough reputation yet). I got wrong, much worse, results;
- Tried to average basis vectors for vertexes are used in multiple faces;
- Tried to average basis vectors for vertexes that have same world coordinates (this would be obviously wrong solution, but I've tried it anyway).


texts: Unity3D playing sound when Player collides with an object with a specific tag

texts:
I using Unity 2019.2.14f1 to create a simple 3D game.

In that game, I want to play a sound anytime my Player collides with a gameObject with a specific tag.

The MainCamera has an Audio Listener and I am using Cinemachine Free Look, that is following my avatar, inside the ThridPersonController (I am using the one that comes on Standard Assets - but I have hidden Ethan and added my own character/avatar).

The gameObject with the tag that I want to destroy have an Audio Source:

In order to make the sound playing on the collision, I started by creating an empty gameObject to serve as the AudioManager, and added a new component (C# script) to it:

using UnityEngine.Audio;
using System;
using UnityEngine;

public class AudioManager : MonoBehaviour
{

    public Sound[] sounds;

    // Start is called before the first frame update
    void Awake()
    {
        foreach (Sound s in sounds)
        {
            s.source = gameObject.AddComponent<AudioSource>();
            s.source.clip = s.clip;

            s.source.volume = s.volume;
            s.source.pitch = s.pitch;
        }
    }

    // Update is called once per frame
    public void Play (string name)
    {
        Sound s = Array.Find(sounds, sound => sound.name == name);
        s.source.Play();
    }
}

And created the script Sound.cs:

using UnityEngine.Audio;
using UnityEngine;

[System.Serializable]
public class Sound
{
    public string name;

    public AudioClip clip;

    [Range(0f, 1f)]
    public float volume;
    [Range(.1f, 3f)]
    public float pitch;

    [HideInInspector]
    public AudioSource source;
}

After that, in the Unity UI, I went to the Inspector in the gameObject AudioManager, and added a new element in the script that I named: CatchingPresent.

On the Third Person Character script, in order to destroy a gameObject (with a specific tag) when colliding with it, I have added the following:

void OnCollisionEnter(Collision other)
        {
            if (other.gameObject.CompareTag("Present"))
            {
                Destroy(other.gameObject);
                count = count - 1;
                SetCountText();

            }
        }

It is working properly as that specific object is disappearing on collision. Now, in order to play the sound "CatchingPresent" anytime the Player collides with the object with the tag, in this case, Present, I have tried adding the following to the if in the OnCollisionEnter:

FindObjectOfType<AudioManager>().Play("CatchingPresent");

But I get the error:

  The type or namespace name 'AudioManager' could not be found (are you
  missing a using directive or an assembly reference?)

AudioManager.instance.Play("CatchingPresent");

But I get the error:

  The name 'AudioManager' does not exist in the current context

As all the compiler errors need to be fixed before entering the Playmode, any guidance on how to make the sound playing after a collision between the player and the gameObject with the tag Present is appreciated.


texts: If I were to start an Android or iPhone app or game, what program should I use?

texts:
I don't really know a lot about programming and the only things I do is using codes with Gamemaker, but I have read that it is too basic and it can't be used with iPhone or Android.

Is there anything free that I can use to make games for those platforms? Or if not, any suggestions for engines or anything else? I was wondering about Unity, for example, is that a good investment to use for making games?


texts: How to be sure that a name we came up with for an evil corporation is safe to use in our game?

texts:
I need your advice. We are currently developing a pixel art point and click adventure game. We have an evil corporation in our game and we also came up with a name for it. Now, to be sure that the name has no other firm/corporation we did a google search. There are some that are close to our name but not exact as ours. For example, we replaced an o with 0 and added dots between each letter. Now I have a question for you, how to be 100% sure that the name we came up with is safe to use in our game?

We don't want any problems. I am a bit worried about it.

Also, what happens when we release the game and some firm chooses our name. Personally, I don't care about it, but could they come to us in the future and say that we have no right to use "their" name?

Thanks in advance!


texts: Libgdx - notification popup (something like Toast) - on both Desktop and Android

texts:
I'm trying to implement a notification system with LibGDX. As we know, Android has it's Toast which is great, but I can't use it in Desktop mode.

I tried extending Dialog etc, adding as an actor and it all worked, but there's one problem - it still needs to be within the 'stage' object range, cause I have to add the 'notification actor' to the stage.

Do you have any ideas how to implement it in a static way, that the notification dialog/label/window would be 'callable' from the whole app?

Here's my code:

public class Notification extends Dialog {

public enum NotificationType{
    SUCCESS, FAIL, INFO;
}

static Skin skin = new Skin(Gdx.files.internal("data/notificationskin.json"));
Label label;
public Notification(String text, NotificationType type) {
    super("", skin);
    setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()/10);
    setPosition(0, Gdx.graphics.getHeight() + getHeight());
    label = new Label(text, skin);
    add(label).center();

    label.setColor(Color.BLUE);
    setKeepWithinStage(false);
    show();
}

public void show(){

    MoveToAction moveTo = new MoveToAction();
    moveTo.setPosition(getX(), Gdx.graphics.getHeight() - getHeight());
    moveTo.setDuration(2f);

    MoveToAction moveBack = new MoveToAction();
    moveBack.setPosition(getX(), Gdx.graphics.getHeight() + getHeight());
    moveBack.setDuration(2f);

    SequenceAction action = new SequenceAction(moveTo, Actions.delay(1.0f), moveBack, Actions.removeActor());
    addAction(action);

}
}

To show the toast I need to call:

Notification not = new Notification("You're now connected", SUCCESS);
stage.addActor(not);

which is bad - it should be static.


texts: What is the correct way of changing image of existing CCSprite?

texts:
How do I correctly change sprite to show another image? Or to have another texture?
This is the way I do it now. When I need to change sprite image I increase state variable. So i have one picture for 0, another for 1 and another for 2.
First i tried just saying mysprite = [CCSpriteWithFile:@"sprite.png"] but that didn't end up too well since I was making new objects every frame and it got messy pretty fast.
So I added a check. There is another variable that is stateChanged and it starts at zero. So I compare state to stateChanged before actually making any sprites and if it differs I do the magic.
But here comes the problem. Somehow this sprite won't flip. And I believe the problem is in this method.

- (void) updateState
    {
        if (stateChanged != state) {

        if (state == 0)
            {
                currentSprite = [CCSprite spriteWithFile:@"eggclosed.png"];
                [self addChild:currentSprite];
            }

        if (state == 1)

        {
            currentSprite = nil;
            [self removeAllChildrenWithCleanup:YES];
            currentSprite = [CCSprite spriteWithFile:@"eggopen.png"];
            [self addChild:currentSprite];
        }

        if (state == 2)
        {
            currentSprite = nil;
            [self removeAllChildrenWithCleanup:YES];
            currentSprite = [CCSprite spriteWithFile:@"yoshi.png"];
            [self addChild:currentSprite];
        }

            stateChanged = state;
        }
            }

TLDR: How to correctly change image of sprite. I have a Pet object that has a CCSprite property. And I sometimes need to change sprte to look another way. How do?


texts: How do I get an Android device's screen size in exact pixels?

texts:
On every single android device {emulators} from ldpi to xxhdpi, both DisplayMetrics and native JNI EGL return width:320 and height:526. Even on actual HTC ONE mobile it returns something like 320x526. This is annoying. I need to know the exact pixel dimensions of the GL rendering surface {framebuffer/renderbuffer etc}. How can I do that ?

From Java activity class I am doing:

DisplayMetrics metrics = getResources().getDisplayMetrics();
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;

From the JNI C++ code I am going following with NO luck (again output: Size = 320 x 526):

int W, H;
EGLDisplay display = eglGetCurrentDisplay();
EGLSurface surface = eglGetCurrentSurface(EGL_READ);
eglQuerySurface(display, surface, EGL_WIDTH, &W);
eglQuerySurface(display, surface, EGL_HEIGHT, &H);

LOGI("JNIGlue.cpp:Init:EGL-Width : %d", W);
LOGI("JNIGlue.cpp:Init:EGL-Height: %d", H);

glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &W);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &H);

LOGI("JNIGlue.cpp:Init:RB-Width : %d", W);
LOGI("JNIGlue.cpp:Init:RB-Height: %d", H);

So how do I get the exact OpenGL rendering surface/buffer size ?


texts: Should I accumulate state time based on a global or a parameter?

texts:
Generally, we associate a "state time" with our sprites. Libgdx provides a method to do so:

float deltaTime = Gdx.graphics.getDeltaTime();

However, in the main game loop, we have a delta time as a parameter in render() methods. Suppose my player has states like Idle, WalkLeft, WalkRight, Jump, Hit, and Die. I use the delta time to know how much total time has elapsed within a state:

public void setState (int state){
    float deltaTime = Gdx.graphics.getDeltaTime();
    this.state = state;
    this.stateTime += deltaTime;
}

Is it proper to write this, or I should take the parameter for delta time from the method that calls it?


texts:
I'm using SFML2.0 and am trying to make a wrapper class for my controller/joystick.
I read all the input data from my controller and send it off to my controllable object.

I want to have two types of buttons per button press, one that is continues(true false state ) and one that is an action and is set to false after the next frame update.

Here is an example of how I set my button A to true or false with the SFML api.
Whereas data is my struct of buttons, and A holds my true/false state every update.

data.A = sf::Joystick::isButtonPressed(i,st::input::A);

But I've also added "data.actionA" which represents the one time action state.

Basically what I want is for actionA to be set false after the update its been set to true. I'm trying to keep track of the previous state. But I seem to fall into this loop where it toggles between true and false every update.

Anyone an idea?


texts:
I have four bodies in my Box2D World.  Each are polygon shape, with some physics parameters.

Now when the game start, I need one of the bodies from the World (BodyA) to not be allowed to collide with another (BodyB).  It should be allowed to collide with others.

To clarify, BodyA and BodyB cannot collide with each other, but can collide with rest of the bodies in the Box2D world.

How could make this kind of mechanism in Box2d ?

Please help me about this query.
Thanks & Regards,


texts: Serious gameplay issue by spawning enemies according to elapsed time

texts:
EDIT: I have changed the title as I think that this is a general gamedevelopment question but, on a technical note, I am using Cocos2d v2.0

Some time ago I had asked a question on which was the most efficient way/method to spawn enemies.

I have choosen to spawn my enemies on the "update" cycle of the main GameScene. In short: at each update call every single enemy in the enemy array is checked and if the enemy has not spawn and the total elapsed time is greater than the current time then the enemy will spawn.

I have realized only now that basing the spawn time on the total elapsed time has the following drawback.

For example, in a vertical scrolling shooter game, ff the frame rate is very low (e.g. 20 fps) then the spawn position will be much different from each other.

I have "planned" and "engineered" my gameplay around 60fps, so if for any chance there is a framedrop then the user will have a different user experience also in terms of enemy spawn position (normally, in those "bad" cases the user should be affected only by the lower frame rate but here is actually getting a different game - in certain cases easier in other cases more difficult).

On the bright side I have been using Cocos2d 2.0 that limits the game to only more powerful devices plus I have optimized my game quiet a lot (use of spritebatch nodes and pvr.ccz compressed images) which means that on avarage the game is running relatively fast.

Remains the drawback that we are talking about "avarage fps" and hence different users with different iPhones will have different spawning positions of enemies.

Any suggestion to limit this drawback?
Am I the only one experiencing/noticing this?


texts:
This is a noob question but, what is the rigidbody movement equivalent of:

transform.position += transform.right * speed * Time.deltaTime;