texts: How to apply forces to character with gamepad in Unity?

texts:
I've been following Brackey's tutorial on this, see the excerpt from my code below. In his tutorial it only teaches "transform.Translate", how do I use this gamepad input system tool to add forces to the character to make them move instead? So I can have jump physics, and when they're in space they'll keep the momentum.
{
    NewControls controls;

    Vector2 move;
    Vector2 rotate;
    private void Awake()
    {
        controls = new NewControls();

        controls.Gameplay.Jump.performed += ctx => Jump();

        controls.Gameplay.Walk.performed += ctx => move = ctx.ReadValue<Vector2>();
        controls.Gameplay.Walk.canceled += ctx => move = Vector2.zero;

        controls.Gameplay.Rotate.performed += ctx => rotate = ctx.ReadValue<Vector2>();
        controls.Gameplay.Rotate.canceled += ctx => rotate = Vector2.zero;
    }

    private void Update()
    {
        Vector2 m = new Vector2(move.y, move.x) * Time.deltaTime;
        transform.Translate(m, Space.Self);**

        Vector2 r = new Vector2(rotate.y, rotate.x) * 100f * Time.deltaTime;
        transform.Rotate(r, Space.Self);
    }
}

To move with rigidbody controls, you have to use things like “forward” or “left” but I want one joystick to control the forward, backwards, and side to side movements. I don’t know how to use the joystick input for moving in all those directions. The tutorials have them as separate arrow keys
does anyone have some sample code, or a tutorial to point me to, or just some explanation?  it would be much appreciated.


texts: I am fairly new to Unity3D experience , but I have a very good knowledge of Java and Android development. I am really confused that if Java is at all needed for developing android applications? I read somewhere in Unity documentation that adding behaviour to objects in Unity requires use of scripts, and that unity only supports C# , .Net , and Boo scripts. Is there no use of Java at all?


texts:
I've been writing a simple top down mini RPG in python.

My problem is that when I move the player I have to repeatedly tap the arrow key. Each time I tap the key the player moves 5 PX in the direction of the key I press, but if I hold down the key he doesn't keep moving, he just moves the first 5 PX.

My moving code looks like this:

# event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:          # check for key presses
            if event.key == pygame.K_LEFT:        # left arrow turns left
                x = x + -x_speed
            elif event.key == pygame.K_RIGHT:     # right arrow turns right
                x = x + x_speed
            elif event.key == pygame.K_UP:        # up arrow goes up
                y = y + -y_speed
            elif event.key == pygame.K_DOWN:     # down arrow goes down
                y = y + y_speed

And farther up I define the x_speed ect.

How do I make it keep moving when I hold down the key?


texts:
I'm trying to make a shader and I need a fullscreen quad to do so.

I have everything set up and working, but when I render the quad it appears as a small square. This would probably be because I'm passing the cameras world, projection and view matrix into the shader and so the quad appears as a normal object. If I remove this it doesn't appear at all.

How do I go from it rendering as a part of the scene which moves with the camera to being something that completely covers the screen?

edit:

Vertices:

new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 0)),
new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 0)),
new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 1)),
new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 1))

Indices:

ushort[] indices = { 0, 1, 2, 2, 1, 3 };

Render:

        for (int l = 0; l < loader.GlowShader.CurrentTechnique.Passes.Count; l++)
        {
            //loader.GlowShader.Parameters["World"].SetValue(camera.World);
            //loader.GlowShader.Parameters["View"].SetValue(camera.View);
            //loader.GlowShader.Parameters["Projection"].SetValue(camera.Projection);
            loader.GlowShader.Parameters["glowTexture"].SetValue(renderTargetTexture);

            loader.GlowShader.CurrentTechnique.Passes[l].Apply();
            renderQuad.Render();
        }


texts: Floating point precision issue with Box2D

texts:
I'm using Box2D and I am putting edge tiles as b2Bodies so that the tile world can have physics:

The problem is that there are 3 b2_kinematic bodies under the player right beside each other.
Every so often, he gets stuck like in this image (as if there were a very very small slope) and the player box gets stuck. I have to move him back a little to overcome it.
The player has fixed rotation which is what also causes this.
I'm not sure how to fix this.
Any ideas?
Thanks


texts: How to associate entities in a Entity Component System (Artemis)

texts:
I want to implement an association between 2 entities in a ECS architecture using Artemis framework, which handles Components, Entities and Systems very well for me.

I have an entity "Empire" (with several components like Empire ID, researched technologies, etc), and I would wish to establish "diplomacy" between 2 Empires (War, Peace).

In which way could I implement that with an ECS architecture? I know about unite components, but not relating entities.

Thank you


texts: Unity: Keyboard Shortcut to Deselect Game Object

texts: How do you unselect a game Object in the 3d view using your keyboard?


texts: How much to bake user input in a client-server?

texts:
Assume a client-server game where there server manages all state and the clients are simply rendering / input.

How much should I bake user input from the client before sending it off to the server?

Does it make sense to send "jump" or "space keydown"?

I'm inclined to bake the input as much as possible.  Am I setting myself up for pain later?


texts: When creating a UI scene in Unity, should I render the canvas in camera space?

texts: I'm working on a scene that is strictly going to be used for character creation.  Can anyone explain what the best practice is for a scene like this?  Should I render the canvas to the camera, or should I render it in world space, or as an overlay?


texts:
Im making a tree in blender with the sappling add-on,  i've already textured the leaves, i want to know how to texture the trunk with a bark texture. Im using cycles render.

Thanks in advance. :)


texts:
I have an 2-dimensional planet at coordinate (pX, pY) and an object at the surface of the planet at some coordinates (oX, oY). I want to have the object go left or right when the user press the keys, which I'd like to simulate by applying a force. I have a homemade physics engine built and all I'm missing is the x/y amounts to use to apply the force in a tangential direction.

What calculation is needed to apply a tangential force clockwise/counterclockwise on an object at (oX, oY) around a center of (pX, pY)?


texts: How do commercial games engines organise the index/vertex buffers?

texts:
Preface: This question is going to be coming from a Direct3D point-of-view, because that's what I'm familiar with.

Obviously we incur a slight overhead every time we change the vertex or index buffers in Direct3D (i.e. with IASetIndexBuffer). But I suppose if we allocate one giant index/vertex buffer we'll end up having to manage the memory manually, and sort of end up with a fragmentation problem (or pauses while we swap all the data around).

So how do commercial engines load/unload data? I'm sort of leaning towards a 'package' based approach, so a 'package' of models has its own vertex/index buffer that we can load/unload as the package is no longer needed; and then try to draw all instances from the same package together.

But I'd be interested to hear what the accepted/standard way of handling this is?


texts:
I started learning OpenGL and GLUT by making a snake game. The problem I encountered is that when I press the "new game" in the menu, the window has to be resized so that the content of the window to be updated.

From what I have read, it's because of the MainLoop that's waiting for an event, but I don't know how to fix it. I've tried with glutPostRedisplay, but it doesn't change anything; maybe I'm placing it wrong. Here is the code associated with the restart of the game:

int main( int argc, char** argv ) {
  glutInit( &argc, argv );
  glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB );
  glutInitWindowSize( 800, 600 );
  glutInitWindowPosition( 100, 100 );
  glutCreateWindow( "Aarghhh! O ramaaa !" );
  createMenu();
  glClearColor( 0.0, 0.0, 0.0, 0.0 );
  init();
  glutReshapeFunc( reshape );
  glutDisplayFunc( dreptunghi );
  glutSpecialFunc( player );
  glutMainLoop();
  return 0;
}

void init( void ) {
  glClearColor( 1.0, 1.0, 1.0, 0.0 );
  glMatrixMode( GL_PROJECTION );
  gluOrtho2D( 0.0, 800.0, 0.0, 600.0 );
  glShadeModel( GL_FLAT );
}

void menu( int num ) {
  if ( num == 0 )
    exit( 0 );
  else {
    if ( num == 1 ) {
      menu_value = num;
      snake.clear();
      i = 30.0;
      j = 30.0;
      alpha = 1.0;
      value = -1;
      speed = 3;
      eaten = true;
      collided_food = false;
      collided_self = false;
      createMenu();
      glClearColor( 0.0, 0.0, 0.0, 0.0 );

      init();
      glutDisplayFunc( dreptunghi );
      glutReshapeFunc( reshape );
      glutSpecialFunc( player );
    }
  }
  glutSwapBuffers();
  //glutPostRedisplay();
}

void createMenu( void ) {
  glutCreateMenu( menu );
  glutAddMenuEntry( "New game!", 1 );
  glutAddMenuEntry( "Exit", 0 );
  glutAttachMenu( GLUT_RIGHT_BUTTON );
}

I have also tried to write a function for the display of the menu, that's called using glutIdleFunc, but it didn't solve anything either.

I have ran out of ideas.


texts: How can i calculate that normal lays in same part of plane with point?

texts: I.e. n0 for A and n1 for B. Plane divided by plane CD.


texts: How precise should timers in update loops be?

texts:
What is the suggestion of "enough precision" in a timer for a fixed game update loop?
Currently I'm testing with this code, but it sometimes misses 1-2 updates @ 50hz. While at 30hz it seems to work perfect. 60hz again is even worse than 50hz. Is this because I have too low resolution on the timer? Is there something I'm missing?


texts:
what is the simplest algorithm for collision detection that respects the following requirements:

The collision is only between cubes that are always aligned with the axis of the world (not rotated).
Collision between frames must be detected. I mean, since the objects of the game may be moving very fast, I can have two objects that in the next frame are not colliding, but that have collided between the current and the next frame.
The movement of the objects is accelerated (we have gravity).
I need to know where did the objects collide (a point coordinate, the time between frames when this collision happened, ...)

Thanks.


texts: In my game I using textmesh, but textmesh has a pixel problem even adjusting scale, character size and font size.  How to solve it?


texts: How do I export Physique animations without breaking them?

texts:
I've been trying to export a simple footstep animation that I made in 3ds Max, but it either fails to export or is broken (imports into unity missing a few frames, or appears to have imported but won't play) every single time.

I've tried .fbx and .3ds, but neither works. I'd rather not use the Skin modifier, because it would require starting from scratch and learning a new system. Any ideas?


texts: How can I refer to Android assets in other directories?

texts:
My project was initially not meant for Android, and its assets are organised along the following directory structure (I hope the ASCII art renders reasonably well):

/
+- engine/
 |    +- src/
 |     |      enginefile1.cpp
 |     |      ...
 |     `- textures/
 |            texture1.tex
 |            ...
+- game/
 |    +- src/
 |     |      gamefile1.cpp
 |     |      ...
 |    +- textures/
 |     |      gametexture1.tex
 |     |      ...
 |    +- ios/
 |     |      [various iOS-specific files]
 |     `- android/
 |           | build.xml
 |           | AndroidManifest.xml
 |           +- jni/
 |           |     Android.mk
 |           +- assets/
 |             [other Android-specific files]
 `- othergame/

My game/android/jni directory is almost empty because Android.mk points to the relative paths of the source files in engine/src and game/src. Actually, it even includes the proper Makefiles so that I never have to modify Android.mk when I add or remove a source file to the project.

Both engine and game provide assets that need to be shipped with the Android build. I would like build.xml to refer to these assets without having to manually copy them. A rule that copies the assets at build time then deletes them would be acceptable, but of course I would prefer a zero copy solution. Does this make sense? How did others solve this cross-platform build problem?


texts: Alternative to unity's character controller

texts:
I wonder what you guy would do for a cheap replacement of character controller in unity. I try a bunch of implementation and they don't work at all, what I'm doing wrong?

I'm trying to make a game with megadrive's sonic pinball physics, think (technically) about mario galaxy meet tony hawk with sonic's high speed. Currently I use a simple raytracing, but I'm looking to listen collision around the sphere collider.

In my case i tried:

Rigidbody turn the game in a slide show, Intel atom n455 for the win (actually I like the limitation so it can run on most machine).
Kinetic body don't collide with scenery (don't listen collision).
Character controller don't rotate.
Sweeptest() and SweepTestAll() but walls and inward curve fails dramatically. + it does not work with the flash preview of unity 3.x

I want to be able to move the character according to tangent of arbitrary complex volumes. For example, taking slope change higher than 90° and leave the case handling with special case code (for example stopping at a wall or falling down a cliff)

What should I do to meet the requirement with good performance?

Currently my code is this one, with sweeptest() which doesn't work:
http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody.SweepTest.html

private void UpdateSurfacePosition()
    {
        Ray//origine, direction
            ground_check_ray = new Ray( gameObject.transform.position, -gameObject.transform.up);// * (Momentum.magnitude + 1));
        RaycastHit
            raycast_result;
        Rigidbody
            rigid_body = gameObject.rigidbody;

        rigid_body.detectCollisions = false;
        rigid_body.isKinematic = true;

        bool onGround;// =
            //Physics.Raycast( ground_check_ray, out raycast_result );//ray, hit
            //rigid_body.SweepTest(-gameObject.transform.up, out raycast_result);//direction, hit, distance

        raycast_result = new RaycastHit();
        RaycastHit[] contacts = rigid_body.SweepTestAll(-gameObject.transform.up);

        rigid_body.SweepTest(-gameObject.transform.up, out raycast_result);

        if (contacts.Length > 0)
        {
            onGround = true;
            int i=0; while (i != contacts.Length)
            {
                raycast_result.normal += contacts[i].normal;
                i++;
            }
            raycast_result.normal = raycast_result.normal.normalized;
        }
        else
        {
            onGround = false;
        }

        debug1 = "Normal > " + raycast_result.normal.ToString()
            + " Position > "+ raycast_result.point.ToString()
                //+" transform > "+ raycast_result.transform.name.ToString()
                + " Contact > " + contacts.Length
                ;

        if ( onGround )
        {
            Vector3
                next_position;

            //UpdateOrientation( gameObject.transform.forward, raycast_result.normal );

            UpdateMoveOrientation( gameObject.transform.forward, raycast_result.normal );
            next_position = GetNextPosition( raycast_result.point );
            rigid_body.MovePosition( next_position );

            //ground_direction = raycast_result.normal;
        }
        else//onAir
        {
            //if forward close to dot.Y = abs(1) choose -up if 1 and up if -1
            UpdateMoveOrientation( gameObject.transform.forward, raycast_result.normal );
        }
    }


texts: how to temporarily turn off/on multisampling for an OpenGL ES 2.0 render context in Android?

texts:
In my OpenGL ES 2.0 Android app, I render to an EGL surface with >= 2 samples; I obtain this surface by passing:

EGL14.EGL_SAMPLES, 2

as part of the attribute_list argument for egl.eglChooseconfig() in my GLSurfaceView.EGLConfigChooser.

(How) can I temporarily turn off multisampling for this render context?

For example, I sometimes use the same render surfacebetween frames to render my scene in flat fake colors for a picking feature, in which case multisampling it as least unnecessary. When I enable

  [x] Force 4x MSAA

in Android's developer options, I read back values completely out of the range that I've rendered, which for some reason doesn't happen otherwise on my multisampling surface.

Notes:

If possible, I'd like to avoid creating another (off-screen) render context without multisampling because it's extra work to manage its lifecycle and to communicate between the two threads. (The extra time for the occasional render pass on my main render surface is small enough to be okay).
glDisable(GL_MULTISAMPLING) doesn't work on Android because the constant GL_MULTISAMPLING is not defined in either GLES20 nor GLES30.
There is a constant EGL14.EGL_MULTISAMPLE_RESOLVE but as far I know, that can be used only to query rather than to set, the surface's multisample strategy, and neither of the two possible values mean "off".

Any ideas?


texts: How to calculate plane corner vertices from plane origin point and plane normal?

texts: I have an origin point, and normal vector of a 3D plane. I want to calculate 4 vertices to use as the corners of a 2 triangle quad to render the plane.


texts: How can I compute the distance between two actors in Stencyl?

texts:
How do U use the "distance" behavior in Stencyl?

I need to know the distance between two actors in order to start a timer.


texts: The General Idea Behind Google Game Services Turn-Based Matchmaking

texts:
I am just starting to develop a Turn-Based game with the Google Play Game Services, and I am utterly confused about the steps to initiate the match.

My game has a maximum of 2 players at once, and I am using the default UI for match-making.

How can I actually wait for the another player to join? My game currently "starts", even with only the local player.. meaning: Why is the "match initiated callback" invoked, even if no another player has even joined the game? What event is invoked when another player joins the game, so I can possibly display a "waiting for another player" UI? Should I have a need for such an UI? I have this nagging feeling that I am misunderstanding something essential here.


texts: Press f to interact with NPCs or objects

texts:
How do I change the method used for initiating the interaction. Instead of clicking object, check if within a certain radius of an object when you hit a key on your keyboard.

If within 1 unit, the player gets a message that they can press f to interact. When f is pressd, get the object they're close to and handle the interaction the same way.

PS. I'm using box collider.

Here are the script that I found. I tried this but once I start the game and press F key, its working. But I want the player to press the F key once the character is inside the collider of an object.

WorldInteraction

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

public class WorldInteraction : MonoBehaviour {
    NavMeshAgent playerAgent;

void Start() {
    playerAgent = GetComponent<NavMeshAgent>();
}

void Update() {
    if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) {
        GetInteraction();
    }
}

void GetInteraction() {
    Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit interactionInfo;
    if(Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity)) {
        GameObject interactedObject = interactionInfo.collider.gameObject;
        if (interactedObject.tag == "Interactable Object") {
            interactedObject.GetComponent<Interactable>().MoveToInteraction(playerAgent);
        } else {
            playerAgent.destination = interactionInfo.point;
        }
    }
}

}

Interactable

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

public class Interactable : MonoBehaviour {
    public NavMeshAgent playerAgent;

public virtual void MoveToInteraction(NavMeshAgent playerAgent) {
    this.playerAgent = playerAgent;
    playerAgent.destination = this.transform.position;

    Interact();
}

public virtual void Interact() {
    Debug.Log ("Interacting with base class.");
}

}

NPC

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

public class NPC : Interactable {

public override void Interact() {
    Debug.Log ("Interacting with NPC.");
}

}


texts:
I am trying to change depths/ layers of my gameobjects inside the game using flash. To be more specific, I have a horse object and a fence object. I set them up initially on stage and the horse layer is in front of the fence which is correct like shown below

Now at some point in my game, the horse moves behind the fence. So the Fence layers should now be in Front. Right now, when the horse moves behind the fence, it is still in front because of course its layers has not changed like shown in image below. How do I control this using ActionScript?

Hope someone could throw some ideas here!


texts: Why does Input.GetKey("enter") never return true?

texts:
I want to modify an int variable on one script by having another script subtract 1 from it. But when I try to trigger this on an "enter" key press, nothing happens.

1st script:

public class spawnenemy : MonoBehaviour {

    public int enems = 1;

2nd script:

public class collisions : MonoBehaviour {

private spawnenemy enems;

void Start () {
    enems = gameObject.GetComponent<spawnenemy> ();

  }

void FixedUpdate(){
  if (Input.GetKey("enter")){
   enems.enems--;
 }
}

Thanks.


texts:
I have been writing 2D iOS games for a while and I'm looking into getting into 3D. I want to know if Maya is required for making 3D sprites or if you can easily make your 3D sprites using just Unity 3D.

They won't be detailed, just about the size / shape and detail level of Crossy Road sprites


texts: Calculating damage reduction of armor parts

texts:
I am currently implementing a turn-based puzzle/RPG game.
The situation now is the following: The player can have up to 4 armor parts: Helmet, Gloves, Trousers and upper-body-armor.
I actually planned to calculate the damage reduction like this:
ActualDamage = Damage*(1-helmetReduction-gloveReduction-trousersReduction-upperArmorReduction)

But I see some problems with that: If the player collects 4 armor parts with, let's say 0.3, 0.4, 0.2, 0.1 reduction, then the damage will be removed completely.
This is not what I want to achieve.
So I am no looking for a way to consider all armor parts, but have a different formular for calculating then together.
I know a way would be to have an upper limit of damage reduction, but that seems like a dirty hack for me.

I know there are games which already do this (e.g. Diablo 3). In Diablo 3 all armor parts add to the global toughness value which then seems to reduce the damage.
How could such a thing be done for example?

Edit:
To clarify: I am acutally looking for a way/formula which takes every armor piece into account and gives an overall damage reduction value, which is, in every case < 100%.


texts: Unique_ptr game state vs shared_ptr game state

texts:
I have this (typical) base class:

class GameState
{
 public:
    GameState(){}
    GameState(GameState&& other) = default;
    GameState& operator=(GameState&& other) = default;
    virtual ~GameState() {}

    virtual int getStateID         ()const = 0;

    virtual bool onEnter           ()      = 0;
    virtual bool onExit            ()      = 0;

    virtual void update (Game& game)       = 0;
    virtual void draw              ()      = 0;

    virtual void shutDown          ()      = 0;
}

And this is a state inherited from GameState base class:

class gGameStateSplash : public GameState
{
    static bool firstSplash;
    int msplashID;
    uint32_t splashStart;
public:
    gGameStateSplash     () :GameState(), msplashID(SPLASH), splashStart(0) {}
    gGameStateSplash(gGameStateSplash&& other)
    {
        firstSplash = std::move(other.firstSplash);
        msplashID   = std::move(other.msplashID);
        splashStart = std::move(other.splashStart);
    }

    gGameStateSplash& operator=(gGameStateSplash&& other)
    {
        firstSplash = other.firstSplash;
        msplashID   = other.msplashID;
        splashStart = other.splashStart;
        return *this;
    }
    ~gGameStateSplash    ()                                                 {}

    int getStateID       ()const override { return msplashID; }

    bool onEnter         ()override;
    bool onExit          ()override;

    void update(Game& game)override;
    void draw            ()override;

   void shutDown         ()override;
};

And this 'GameStateMachine' which use states inherited from GameState:

class GameState;
class Game;

class GameStateMachine
{
    std::vector<std::unique_ptr<GameState>>mvGameStates;

public:
    GameStateMachine():mvGameStates(){}
    GameStateMachine(GameStateMachine&& other){ mvGameStates = std::move(other.mvGameStates);}
    GameStateMachine& operator=(GameStateMachine&& other) { mvGameStates = std::move(other.mvGameStates);  return *this; }
   ~GameStateMachine(){}

    void pushState(std::unique_ptr<GameState> pState);
    void changeState(std::unique_ptr<GameState> pState);
    void popState();

    void update(Game& game);
    void render();
    void cleanAndExit();
};

And instance of GameStatesMachine is used by Game class to update game. As you can see neither GameStates nor GameStatesMachine has members too fancy, just a couple of integers and some boolean.
I use VS 2019 and the program does not compile and throws compilation error c2280 pointing to the GameStates vector of GameStateMachine. I have read Microsoft documentation about it as well as several posts in StackExchange. As read, unique_ptr can not be copied and a move constructor must be implemented in order to do it and to avoid the compiler generates one itself and mark it as delete. So i have implemented move constructor in GameState base class and all inherited states classes. Nothing works. I implemented move constructor also in GameStateMachine with the same result.
But if i change unique_ptr to shared_ptr the error vanishes and all compiles and works as expected. I want to use unique_ptr because i think the states are  going to be owned only by Gameclass, so why waste memory using a shared_ptr?. Am i wrong?


texts: Can I use Playstation controller button icons in my game?

texts:
I'm currently working on a game that will be released on PC with controller support, and I'm trying to find a way on how to best represent controller icons within the game.

I'm assuming I can't simply use Playstation or Xbox controller icons in my game without having some form of license first (right?).

So how would it be best to convey something like 'Press X to interact' in a PC game for controllers?


texts: When should I represent points and sizes as structures?

texts:
As part of my simple Ruby 2D game development framework, my game objects have position (x and y values) and size (width and height).

class MyGameObject
  attr_accessor :x
  attr_accessor :y
  attr_accessor :width
  attr_accessor :height
  ...

Another approach I've seen was treating the position as a Point structure, and the size as a Size structure:

Point = Struct.new(:x, :y)
Size = Struct.new(:width,:height)

class MyGameObject
  attr_accessor :position   # Point instance
  attr_accessor :size       # Size instance
  ...

Some frameworks use the former (I think GDX, Gosu...). Others use the latter (cocos2d-iphone). The problem is, it isn't entirely clear to me the advantages and disadvantages of both behaviors (in game development) - I don't know why some frameworks chose one and not the other.

Are there significant differences I should consider?


texts: libgdx - #iterator() cannot be used nested

texts:
I'm getting this error when I try to check if any of the targets overlap each other:

iterTargets = targets.iterator();
while (iterTargets.hasNext()) {
    Target target = iterTargets.next();

    for (Target otherTarget:targets) {
        if (target.rectangle.overlaps(otherTarget.rectangle)) {
            // do something
        }
    }
}

So I can't do that? How am I supposed to check each member of an array to see if it overlaps any other member?


texts: What are the steps taken by this GLSL code?

texts:
1 void main(void)
 2 {
 3     vec2 pos = mod(gl_FragCoord.xy, vec2(50.0)) - vec2(25.0);
 4     float dist_squared = dot(pos, pos);
 5
 6     gl_FragColor = (dist_squared < 400.0)
 7         ? vec4(.90, .90, .90, 1.0)
 8         : vec4(.20, .20, .40, 1.0);
 9 }

  taken from
  http://people.freedesktop.org/~idr/OpenGL_tutorials/03-fragment-intro.html

Now, this looks really trivial and simple, but my problem is with the mod function.

This function is taking 2 vec2 as inputs but is supposed to take just 2 atomic arguments according to the official documentation, also this function makes an implicit use of the floor function that only accepts, again, 1 atomic argument.

Can someone explain this to me step by step and point out what I'm not getting here?

It's some kind of OpenGL trick? OpenGL Math trick? in the GLSL docs i always find and explicit reference to the type accepted by the function and vec2 it's not there.


texts: Swapping in game currency for virtual goods. Client vs server. Best practice

texts:
I currently use a server back end to verify my managed in app currency purchases and update the user's coin value.

But what's the best practice to then deal with "in game purchases" where players swap their coin for virtual goods such as power ups etc.

I just realised that if I do it in the app then potentially a hacker could just remove the code so that they can buy some coins once then just perpetually buy whatever virtual goods they want.

Should I let my server back end deal with this instead, which would definitely solve the problem. Is this the best practice?


texts: Changing sprite animation depending on direction

texts:
I'm working on an android game where my sprite is controlled by a joystick. I just added an animation to my sprite with 4 rows and 3 columns:

Now I want to change the animation of my sprite depending on its direction. How do I calculate the direction of my sprite?

This is my controls:

public void update(MotionEvent event)
{
    // drag and drop
    if (event.getAction() == MotionEvent.ACTION_DOWN)
    {
        _dragging = true;
    }
    else if (event.getAction() == MotionEvent.ACTION_UP)
    {
        _dragging = false;
    }

    if (_dragging)
    {
        // get the pos
        _touchingPoint.x = (int) event.getX();
        _touchingPoint.y = (int) event.getY();
        // get the angle
        double angle = Math.atan2(_touchingPoint.y - inity,
                _touchingPoint.x - initx) / (Math.PI / 180);

        // move the beetle in proportion to how far
        // the joystick is dragged from its center
        _pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                * (_touchingPoint.y / 70);
        _pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (_touchingPoint.y / 70);
    }
}

And this is the drawing method in my sprite-class:

private void update()
{
    currentFrame = ++currentFrame % BMP_COLUMNS;
}

public void draw(Canvas canvas, int x, int y)
{
    update();
    int srcX = currentFrame * width;
    int srcY = 1 * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, src, dst, null);
}


texts:
I am trying to build a card based game in which a card is added to player after every round. To win the match player has to remove all cards from his deck. However I have also drawn some additional button for some other purposes. The issue is that when the number of cards got high, they hide behind the buttons like below image.

Is there any way through which i can draw the bitmaps in a fixed area? Something like below image (highlighted rectangle behind the card images).

Following is my code to draw Bitmaps for one player

private void setMainPlayer() {
    //    Log.d(TAG, "Inside Set Main Player Method");
    Card localcard = null;
    Bitmap localimage = null;
    int currentiteration = 0;
    int Card_Gap = Screen_Width / 10;
    int Down_Card_Gap = 0;
    int Down_Card_Gap_positive = 0;
    int Down_Card_Gap_negative = 0;
    playerList.get(0).sortBySuit();

    //  Log.d(TAG,"Main Player Deck size"+MainPlayer.Count());
    while (currentiteration < playerList.get(0).decksize()) {
        localcard = playerList.get(0).getCard(currentiteration);
        localcard.setCurrent_Y(Screen_Height - localcard.getImage(context, Card_Width, Card_Height).getHeight());
        playerList.get(0).setCurrentCard(localcard, currentiteration);
        currentiteration++;
        if (Down_Card_Gap >= 0) {
            Down_Card_Gap_positive = Down_Card_Gap;
            localcard.setCurrent_X(Screen_Center_X + Down_Card_Gap_positive);
            Down_Card_Gap += Card_Gap;
        } else {
            Down_Card_Gap_negative = Down_Card_Gap;
            localcard.setCurrent_X(Screen_Center_X + Down_Card_Gap_negative);
        }
        Down_Card_Gap *= -1;

    }

}

private void DrawMainPlayerDeck(Canvas canvas) {
    // Log.d(TAG, " Inside Draw Main Player Deck");
    Card localcard;
    int currentiteration = 0;
    while (currentiteration < playerList.get(0).decksize()) {
        localcard = playerList.get(0).getCard(currentiteration);
        canvas.drawBitmap(localcard.getImage(context, Card_Width, Card_Height), localcard.getCurrent_X(), localcard.getCurrent_Y(), null);
        currentiteration++;
    }

}

I am drawing bitmaps on surfaceview.

Any suggestion (even if it involves a game engine like libGDX) would be really helpful.


texts: How do I calculate the bounce vector of a ball hitting the starting point of a segment?

texts:
I have a ball (with parameters x, y, radius) that travels on the screen (with vectors directionX directionY) and can collide with a segment with random slope (with parameters startX, startY, stopX, stopY).

After i detect the collision i split code for calculate bounce vector in two different situations: first situation is ball in the middle of the segment (which is now working properly) and second is ball colliding the segment corners (starting or ending point) of a segment. Now,my algorythm is more or less working but sometimes there is some wrong behaviour and bounce is wrong or even no bounce (ball pass through the line without bounce)

This is the code i'm currently using:

       if (Math.pow(line.startX - x, 2) + Math.pow(line.startY - y, 2) <= Math.pow(radius, 2) || Math.pow(line.stopX - x, 2) + Math.pow(line.stopY - y, 2) <= Math.pow(radius, 2)) {
          // ball has hit the corner of the segment
           if (Math.pow(line.startX - x, 2) + Math.pow(line.startY - y, 2) <= Math.pow(radius, 2)){
               //calculate bounce vector with starting point of segment
                float x1 = x - line.startX;
                float y1 = y - line.startY;
                float c1 = (float) (-2 * (directionX * x1 + directionY * y1) / (x1 * x1 + y1 * y1));
                directionX += c1 * x1;
                directionY += c1 * y1;

           }
           else{
               //calculate bounce vector with ending point of segment
                float x1 = x - line.stopX;
                float y1 = y - line.stopY;
                float c1 = (float) (-2 * (directionX * x1 + directionY * y1) / (x1 * x1 + y1 * y1));
                directionX +=  c1 * x1;
                directionY +=  c1 * y1;
           }
        }

      else
            {
 //other code for calculating bounce vector after collision inside segment.

}


texts: Converting world space coordinate to screen space coordinate and getting incorrect range of values

texts:
I'm attempting to convert from world space coordinates to screen space coordinates.

I have the following code to transform my object position

Vector3 screenSpacePoint = Vector3.Transform(object.WorldPosition, camera.ViewProjectionMatrix);

The value does not appear to be in screen space coordinates and is not limited to a [-1, 1] range.

What step have I missed out in the conversion process?

EDIT:

Projection Matrix

Perspective(game.GraphicsDevice.Viewport.AspectRatio, nearClipPlaneZ, farClipPlaneZ);

    private void Perspective(float aspect_Ratio, float z_NearClipPlane, float z_FarClipPlane)
    {
        nearClipPlaneZ = z_NearClipPlane;
        farClipPlaneZ = z_FarClipPlane;

        float yZoom = 1f / (float)Math.Tan(fov * 0.5f);
        float xZoom = yZoom / aspect_Ratio;

        matrix_Projection.M11 = xZoom;
        matrix_Projection.M12 = 0f;
        matrix_Projection.M13 = 0f;
        matrix_Projection.M14 = 0f;

        matrix_Projection.M21 = 0f;
        matrix_Projection.M22 = yZoom;
        matrix_Projection.M23 = 0f;
        matrix_Projection.M24 = 0f;

        matrix_Projection.M31 = 0f;
        matrix_Projection.M32 = 0f;
        matrix_Projection.M33 = z_FarClipPlane / (nearClipPlaneZ - farClipPlaneZ);
        matrix_Projection.M34 = -1f;

        matrix_Projection.M41 = 0f;
        matrix_Projection.M42 = 0f;
        matrix_Projection.M43 = (nearClipPlaneZ * farClipPlaneZ) / (nearClipPlaneZ - farClipPlaneZ);
        matrix_Projection.M44 = 0f;
    }

View Matrix

        // Make our view matrix
        Matrix.CreateFromQuaternion(ref orientation, out matrix_View);

        matrix_View.M41 = -Vector3.Dot(Right, position);
        matrix_View.M42 = -Vector3.Dot(Up, position);
        matrix_View.M43 = Vector3.Dot(Forward, position);
        matrix_View.M44 = 1f;

        // Create the combined view-projection matrix
        Matrix.Multiply(ref matrix_View, ref matrix_Projection, out matrix_ViewProj);

        // Update the bounding frustum
        boundingFrustum.SetMatrix(matrix_ViewProj);


texts: How should I handle "real time" events in an online strategy game?

texts:
Some online strategy games have real time events. For example when you send troops to attack somewhere, the attack happens at the right time in the future. Checking the database again and again to get the list of attacks happening each second would cause heavy load. Is there any technique to achieve this goal?

Another example: You want to attack a village 3 hours away, you send troops and the attack occurs 3 hours later. Should there be an script to check the database at each second to run the query at the specified time?


texts: What are developers using for voice chat on Windows?

texts: On Xbox360 XHV2 is used for dealing with voice data, and XAudio2 is used for the low-level processing of that data. What is the XHV2 equivalent under Windows, assuming FMOD is used for the low-level audio processing? Previously DirectPlay.Voice was used to facilitate this.


texts: In a GUI, should input be handled when the button is pressed or released?

texts: In the menu system for our game (selecting levels, options, etc.), the player presses the a button on the gamepad to go to the next screen. I coded the menu system to wait until the button is released before taking any action (i.e., displaying the next screen). Some recent playtest feedback suggested that we do it the opposite way: take action as soon as the button is pressed.  I am curious, what is the standard way this is handled, and does it even make a difference?


texts: Game programming course materials: What should it include?

texts:
I am tasked to create the course materials for a game programming class, and I’d like your opinion on what aspects and areas of game programming, such as game state management, game object storing or simple AI, should I include in it? The course is intented to be the first step into game programming for students with novice skills in programming.

There will be mathematics as well, but I found that there are multiple questions, with good answers, on that subject already.


texts: I'm a tad confused about the turn based option with iOS5. Does this take care of everything needed to make a multiplayer turn based game?i.e all the game turn data is stored with apple or do I need to still provide a server for something?


texts: Help me please to choose proper path-finding algorithm

texts:
I am new to game development and just want to ask for advice. I need to know which path-finding algoritm will be suitable for my scenario:

Units - any shape. But in most cases rectangles of different sizes.
I have random generated maze and destination point or area.
Because of different maze borders not all unit can fit and move to the end.

How to find path from unit to destination area and check that shape can move to this area?


texts: Modeling player mechanics with a finite state machine

texts:
I have three states

standing
walking
jumping

When I press D standing transitions to walking. The velocity will be set to a defined value and the player moves.

When I release D walking transitions back to standing, which sets the velocity back to 0.

When I press W and the state is walking it transitions to jumping, but when the player hits the ground, it goes back to standing.

jumping has a transition land that always leads to standing because a state doesn't know about its previous states.

Since standing sets a velocity of 0 the player stops walking, when he hits the ground.

How do I prevent this?


texts:
I've been using a tilemap editor for making levels, but I was wondering if there was a way to use PNG images as the level map, as maps created in tiled editor are graphically uninteresting.

Background: I've recently started 2d game development and have learned basics i.e collision, game loop etc. I am developing game in JavaScript for Windows 8, but c#/c++ would work for me also.


texts: How do game devs optimize their games for new CPUs/architectures?

texts:
I've learned that DirectX helps devs to program games on a variety of hardware. However, that's the visual/graphics side of things.

How do game devs deal with new CPUs or CPU architectures? Is there another API for that? Do they use DirectX for this too? Or do they need to learn the ins and outs of the architecture and program accordingly?

Thanks.


texts:
i have a game use A*, this algorithm find path is good in many case.

But if I could not find the way to the destination, it would have to go through many nodes (my map is in gird format). I am looking for an algorithm to know that if I cannot find the way to the destination, A * algorithm will not work to avoid wasting CPU or then my object will only go straight to the target, when it collision with an object, it will stop. I saw a game like Age of Empires, when the farmer was locked in between the 4 walls, which meant he couldn't go out. If I want him to go to a point outside those four walls, he just goes straight to that point and stops when he hits a wall. If the 4 walls have a hole, he will go there and get there]1
[]2

Thanks everyone !


texts: Unity 4.6: Position jumps when switching Canvas render mode from Overlay to camera in code

texts:
In the project I am currently working on I have two sets of main UI: one set that is on the screen at all times for the players use, and the second set which the player can open and look at to gauge their progress and see things about the game world(think pokedex) . The second set also has 3d models in front of the UI in places. To achieve this, I have a script that changes the canvas render mode to Screen Space - Camera when the 2nd UI opens, and I instantiate a 3d model in front of it. My problem is when I switch the canvas back to Screen Space - Overlay, it jumps down in the corner.

My to switch the canvas mode to Camera is as follows:

 /*--Adjust canvas--*/
     canvas.renderMode = RenderMode.OverlayCamera;
     canvas.planeDistance = canvasPlaneDistance;  //1 in this case

My code to switch the canvas back to overlay looks like this:

 /*--Adjust canvas render mode and position--*/
     canvas.renderMode = RenderMode.Overlay;

I discovered that it seems the problem is because the z pos of the Canvas's Rect Transform changes value when I initially change the render mode and this displaces it when I switch it back. I can adjust it back into position in the code by doing this:

canvas.GetComponent<RectTransform>().localPosition =
         new Vector3(canvas.GetComponent<RectTransform>().localPosition.x,
                     canvas.GetComponent<RectTransform>().localPosition.y,
                     0);

But this causes a disorienting flicker which I would rather avoid. Is there any workaround or fix for this?


texts:
I am a game developer who has always loved the GameCube system. I've been developing games since 2017 and have been self-teaching and learning various coding languages. I know it's officially unsupported now but is there any way I can make games for the platform still? Google has not been of much help to me so far. Do I need a development SDK or a specific game engine for this task?

I'd also like any and all help and resources related to GameCube optical media security bypassing you can find. I am okay with building my game engine from scratch but my biggest problem is that I have no idea how I'm going to get past the disc verification system. I know that Datel has done it with Action Replay and SD Loader but they haven't made it publicly available what process they used. I know it's possible but the furthest I've gotten research-wise is this article I found that shows how Nintendo scrambled the data.

For clarification, I want to make signed games that can be played on an unmodified system. I also want to released boxed games so it is more like a real game release rather than some hobbyist project.


texts: Assertion b2Assert(m_bodyCount > 0) showing an error

texts:
I have the following code for deleting a Box2D body:

void b2World::DestroyBody(b2Body* b)
{
    b2Assert(m_bodyCount > 0);
    b2Assert(IsLocked() == false);
    if (IsLocked())
    {
        return;
    }

    // Delete the attached joints.
    b2JointEdge* je = b->m_jointList;
    while (je)
    {
        b2JointEdge* je0 = je;
        je = je->next;

        if (m_destructionListener)
        {
            m_destructionListener->SayGoodbye(je0->joint);
        }

        DestroyJoint(je0->joint);

        b->m_jointList = je;
    }
    b->m_jointList = NULL;

    // Delete the attached contacts.
    b2ContactEdge* ce = b->m_contactList;
    while (ce)
    {
        b2ContactEdge* ce0 = ce;
        ce = ce->next;
        m_contactManager.Destroy(ce0->contact);
    }
    b->m_contactList = NULL;

    // Delete the attached fixtures. This destroys broad-phase proxies.
    b2Fixture* f = b->m_fixtureList;
    while (f)
    {
        b2Fixture* f0 = f;
        f = f->m_next;

        if (m_destructionListener)
        {
            m_destructionListener->SayGoodbye(f0);
        }

        f0->DestroyProxies(&m_contactManager.m_broadPhase);
        f0->Destroy(&m_blockAllocator);
        f0->~b2Fixture();
        m_blockAllocator.Free(f0, sizeof(b2Fixture));

        b->m_fixtureList = f;
        b->m_fixtureCount -= 1;
    }
    b->m_fixtureList = NULL;
    b->m_fixtureCount = 0;

    // Remove world body list.
    if (b->m_prev)
    {
        b->m_prev->m_next = b->m_next;
    }

    if (b->m_next)
    {
        b->m_next->m_prev = b->m_prev;
    }

    if (b == m_bodyList)
    {
        m_bodyList = b->m_next;
    }

    --m_bodyCount;
    b->~b2Body();
    m_blockAllocator.Free(b, sizeof(b2Body));
}

When I close the game I get an exception, and the debugger points to the first line :

b2Assert(m_bodyCount>0);

What exactly does this mean?


texts: Batching texture to texture rendering in Unity on the gpu

texts:
I'm working on a 2D sidescroller within Unity 5.1. The terrain is intended to be semi-infinite in all 4 directions, procedurally generated using a noise algorithm.

I'm using a 3x3 grid of quads as "chunks" that I shift/update as the camera pans around. The issue I'm having is related to the dynamic texture I have tied to each chunk. When they need to be created rather than just shifted around, I'm not quite sure how to render individual tiles from a single texture to specific locations on another texture without using system memory.

Using setpixels, I believe it is passing color data each apply to the gpu side. Using gui/graphics with a rendertexture to drawtexture or any variants seems to be doing individual draws per call rather than giving me the opportunity to batch them. Using the native gameobjects has FAR too much overhead considering I'm trying to make tiles only be 8x8 pixels in size (meaning higher screen res = more on-screen tiles).

So, is it possible within Unity to do a low level texture to texture render/blit/draw/whatever without pulling texture data into system memory AND still batching same material/texture calls together without having to buy some toolkit from the asset store?

If any of this doesn't make sense, please ask anything you need to be able to help me and I'll update as needed.

Thanks!


texts:
I have a static class that I use to build a 3d character and render the results to a RenderTarget2D which I then return.

I'd like to store the results for later use so I need to make a copy of the returned RenderTarget. To do this I`ve tried both a Quad VertexPrimitive Effect with a tiny copy PixelShaderFunction and a SpriteBatch.Draw.

I think that the Quad render is quicker but no matter how I fiddle, the Quad never seems to get it quite right.

For example, I do use SpriteBatch to pick up a 256*256 area of a large Texture2D backdrop and Draw that to a RenderTarget2D. But if I then send that directly to the Quad render and put that result back in the same place it almost - but VERY annoyingly not quite - fits back perfectly. Using another SpriteBatch.Draw does give a perfect result but I've convinced myself that it is slower.

So my questions are twofold.

1) Is the Quad UserIndexedPrimitive quicker than the SpriteBatch.Draw for multiple iterations?

and

2) Why can`t I get the Quad render to give me back the same image when setting it as the  Effect sampler via Effect.Parameter..SetValue(RenderTarget)?

As ever, Thanks :) Stoort.

Here is the problem in png form.

The left half is the RenderTarget2D before I use a short user Effect
that just does a straight copy using

    return tex2D(texture, coord);

as the only PixelShaderFunction instruction via a quad with

    graphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>
                (PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2);

The source and destination width and height are identical as are all the
RenderTarget2D settings for both.

As you can see the output on the right is blurred and the top and right lines are wrapped from the opposite sides.


texts: I assume scenes are for different levels, but should I use them for menu screens or is there a specific tool for menu screens?


texts: Optimise pathfinding failure - can I reduce the number of sweeps?

texts:
I've got pathfinding working on a simple 2D grid map. NPCs can now move around the board and avoid areas they cannot travel. This works well, and is carried out by a single sweep of the board to calculate the path.

If there is no path to the destination, I want the entities to move as close as possible. I have also accomplished this, and have been able to reuse my pathfinding code for this purpose. Essentially, if the initial sweep fails to find a path, the reverse sweep is carried out, which essentially identifies every area which is reachable by the entity. The distance from each cell to the intended destination is already calculated by the pathfinding algorithm. So then I just sort the array of accessible cells by their distance from the destination, and the first one is the closest to the destination. Then I use the pathfinder function again to calculate a path to that closest point.

This does work flawlessly, but it seems inefficient. The process of a failed path find in summary is:

Sweep the board for a path to the destination (which fails)
Sweep the board a second time to find all cells accessible by the entity
Sweep the board a third time to calculate the path from the entity to the cell which is closest to the destination

I suspect the answer is that this is the only way to accomplish what I want; I need to calculate all three pieces of information ((1) whether a path exists, (2) which cell is closes, and (3) how to get to the closest cell), but I'm far from an expert on these algorithms so if there is a better way I would love to know!


texts:
I'm curious how I could control cars in a racing game.

Should my AI agent control its car with commands like "throttle on 0.35, steereing wheel on 0.5 right, brake on 0.0"? Or should I rather pre-compute a curve the car sticks to, and visuals like front wheels turning are just to make everything looks consistent? Or is there any other way?


texts: Performing image based lighting in an open world game

texts:
I finally have a PBR implementation in an engine that I'm writing for a game I'm developing but I'm stuck on how to use IBL in real situations. Most IBL tutorials use it just to show a single mesh or group of spheres but nothing that I can immediately translate to an in-game application.

So I was wondering, in an open world, how would someone go about implementing image based lighting? Different areas will require different environment maps to be generated and then there's the issue of time of day. I guess for that, you could just use values that you would use in your day and night shader to change the colours being sampled from the environment map but you still have the issue of having a large map.

Update:
I've read about light probes and perhaps that's how this is achieved? Create probes around the whole map and then sample and interpolate between the probes that are near the camera. Is this how large open-world games achieve image-based lighting? This way you can have one light probe based on the skybox and multiple light probes spread across the scene and inside rooms.


texts: Does the latest version of Python have libraries for easy host/server connections?

texts: We're working on a turn-based multiplayer Risk-type strategy game in Pygame, and I was wondering if there were any pre-existing libraries like PodSixNet that worked for Python versions 3 and up that would help with establishing host/client server connections. Does anything like that exist, or do the latest versions of Python/Pygame already have functions or libraries that would help with this sort of thing?


texts: touch mouseOver in createjs - DispatchEvent() not working in iPhone/iOS

texts:
I have recently developed an html5 game using createjs and I am currently in the testing phase. The game seems to work fine in all the devices except for the iPhone. After careful analysis I have come to a conclusion that the dispatchevent(), I'm employing in the code to run the createjs built-in rollover() function which I'm dispatching using the dispatchevent() isn't working in the IOS.Apart from this the game seems to be doing all the other tasks in the ios just fine. But since this is the main functionality I'm kind of stuck. The following is the code snipet where I'm employing the dispatchevent() :

                    if(tile[i][j].name != 4)
                      tile[i][j].addEventListener("click",onTileClick);

                      tile[i][j].defined = true;
                      tile[i][j].tweened = false;
                      tile[i][j].cursor = "pointer";

                      tile[i][j].on("rollover",onTileOver);
                      tile[i][j].on("pressmove", function(evt){
                        var o = stage.getObjectUnderPoint(evt.stageX, evt.stageY);
                        console.log("GET", o, evt.stageX, evt.stageY);

                          o.dispatchEvent("rollover");

                      });
                      tile[i][j].addEventListener("rollout",onTileOut);
                      stage.addChild(tileBg[i][j],tile[i][j]);

Any suggestions in this regard?


texts: Implementing smooth 8 directional movement

texts:
I have my units that i move around my map with path finding. The units can move in 8 directions, currently i have the units moving around the map with a extremely basic check against the unit's current position vs. the next target destination in an array of Vector2s (the path). However, the movement is rather jagged and not very fluid.

Current code (I know its not very good, i did this just to test out the pathfinding really);

 if (Position.X < Path [CurrentPathPoint].X) {
     SpeedDir.X = 1;
 }
 if (Position.X > Path [CurrentPathPoint].X) {
     SpeedDir.X = -1;
 }
 if (Position.Y < Path [CurrentPathPoint].Y) {
     SpeedDir.Y = 1;
 }
 if (Position.Y > Path [CurrentPathPoint].Y) {
     SpeedDir.Y = -1;
 }

 Position += SpeedDir * Speed;

I should mention that im not looking for any sort of rotational movement, just smooth diagonal and directional movement. However, i'm at a lose on how i can achieve that...
So any help greatly appreciated :)!

Edit:
Smooth Transitioning between movements is what i'm looking for. Right now, the units sometimes (not sure how to describe but they "stutter" along), looks like they are shaking when moving. As to what i tried before, i had the position being updated directly in the If statements, that didn't give me any stuttering but did not seem like a good approach so i changed to the one above.


texts: Can I use Unity remote with a Android emulator instead of Android phone?

texts:
Unity Remote is good app. It allows to connect with Unity while you are running your project in Play mode from the editor.

But what if I want to test game but I don't have an Android phone? Yes, it happens ¯\_(ツ)_/¯

I have a great Android emulator: Nox APP Player

The emulator doesn't have USB, so it just show me standsrt text Connect device with a USB cable ..... bla bla bla ...Game in the Unity Editor is running...emulator doesn't display the game.

Can I somehow connect this emulator to unity using Unity Remote? Or using something else? How?


texts: How do I resolve asynchronous client actions against an authoritative server state?

texts:
I have a multiplayer card game which I am in the process of developing.

The game is relatively simple; players have a certain number of cards which they can activate, sell, or use in various other ways.

The game isn't turn based.  Instead, it is asynchronous so that players (A, B, C, and D) all make their choices at the same time. Certain actions will affect the game state.  For example, removing a card from the game or adding a card to the game. Players should always be in sync with each other so that, for instance, Player A cannot use a card that Player B has just removed, as it is no longer present.

Obviously there are situations in which Player A may remove a card at nearly the same time that Player B tries to interact with the same card. How would the server handle this sort of situation?

My original thought is that each client could hash their game state and send it with their command to the server, for example:

Player A - #MYHASH# - Command = Pick Up Card Z

Player B - #MYHASH# - Command = Remove Card Z

The server would then action the first command and regenerate the hash. Upon trying to execute the second command it would notice the hash sent by Player B differs from the current hash, so the server would reject the request.

In the above example Player A would notice nothing and the game would continue normally, but Player B would have to be informed that their action failed.


texts: My player died and if i clicked play in the main it will go to the last scene and say gameover

texts:
I am trying to make a gameover scene where in if the player is game over The game will go back to the main or start up then when I press play it will start new game however if i am game over and go back to main and pressed play it will only show me Game over and wont continue my code is.....
Gameover code..

#pragma strict
import UnityEngine.UI;
private var StopGame: boolean=false;
private var showGUI: boolean=false;
var GUIstop: GameObject;
var StopMenu;
var respawn : Transform;

private var canvas : Canvas;

function Start()
{
canvas = GetComponent.<Canvas>();
canvas.enabled = false;
}

function Update () {

if(HealthControl.LOVES==0){
Pause();

  Application.LoadLevel (0);

}

}
public function Pause()
{
canvas.enabled = !canvas.enabled;
Time.timeScale = Time.timeScale == 0 ? 1 : 0;
}

public function Quit()
{
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}


texts: Do you need to have separate companies to publish different kind of games?

texts:
I'm planning to make my own indie game company as both developer and publisher. As a publisher, I have some question about branding and reputation.

1. Quality:
A publisher have 2 games, they both have good average rating and they want to publish another game, which have less resources and effort. Publisher predicted it won't have as good rating as its previous games, but decided to publish it anyway because it needs money. Is this a bad call? Will having 2 good games and 1 bad games affect reputation? How?

2. Genre:
Is genre matters in reputation? For example, a publisher specialized in publishing RPG games, then suddenly, they publish FPS games. Assuming those games all have good ratings in average, will it affect publisher reputation? How?

3. Age-resctricted content:
Do you need different publisher name to publish adult games? The game is closer to "porn game" rather than "having adult content"; different from what we've seen in ESRB rated "M" games such as The Witcher 3. If a publisher mix their "normal" and "porn" games under the same name, will it affect its reputation? How?


texts: What tools are available for game script writing?

texts:
I'm looking to find some software options on OS X that are geared toward writing game scripts. Features like the ability to craft dialogue trees and other non-linear script formats would be appreciated.

I own Celtx and love its ability to store character information along with various other media assets, but it's very linear and straight, film-style script based which doesn't exactly work well for game applications.

Any dedicated or more appropriate software options out there?


texts:
I'm going to be making a shooter-style game, on a navigatable map (All 2D). I'm a little unsure of how to handle the bullets: I see two main ways i could do it

I could have the bullet's x and y position be updated based on its trajectory, and then draw it using the formula

Screen.x - Bullet.x , Screen.y - bullet.y

This would draw the bullet relative to the players location, so that it would appear on the map

The other main method I am considering is drawing the bullet directly to the map image via the getGraphics() method. However, this seems like it could cause performance issues, as just testing this seemed to lag

(this was my test method)

public void Draw(Graphics g){
    image.getGraphics().drawRect(10,10,10,10);
    g.drawImage(image,0,0,null);
}

Adding in the drawRect line caused considerable lag - removing it made the game run fine

Are either of these a good way to handle drawing projectiles? If not, how else could I do it efficiently?


texts: How to change animation start/end proprieties via script?

texts:
Is there a way of changing the start/end proprieties (Transform, Rect Transform, etc..) of an animation via script? Like, I have 5 objects that start at the same position but should end in different positions, so I would like to change the end positions of each one via script.

As I haven't found a way to do this, I created 5 animations for this, but I'd like to just have one animation and change its proprieties in runtime.


texts: When making 3D model for building, is it better to split it or combine it?

texts: As the title say, when making 3d model for building (example: school, office, etc). Used for FPS game so it must have detail and texture must be vary so it won't look like repeating/reused. Is it better to make the whole building as one model with multiple materials and UV map, or split it to sub model such as a wall, pillar, floor, etc. I want to know which is more practical or better for a game. I want to know why is it better, advantage and disadvantage of both, or if there's a better technique I can use.


texts: How do they keep track of the NPCs in Left 4 Dead?

texts:
How do they keep track of the NPC zombies in Left 4 Dead?

I am talking about the NPCs that just walk into walls or wander around aimlessly. Even though the players cannot see them, they are there (say inside rooms or behind doors). Let's say there's about 10 or so zombies in a hallway and inside rooms. Does the game keep all of those zombies in a list and iterate through giving them commands? Do they just spawn when the user is within a certain radius or reached a special location?

Say you placed the 4 units (controlled by players) on completely different places throughout the map. Let's assume you aren't being swarmed and then you have not killed any of these aimless NPCs. Would the game be keeping track of 10 x 4 = 40 zombies in total?

Or is my understanding completely off?

The reason I ask is if I were to implement something similar on a mobile device, keeping track of 40 or more NPCs might not be such a great idea.


texts: If raycast hit nothing my object stay at end of the ray?

texts:
How to make an object stay at end of the raycast if the ray hit nothing ?!
Here is my script

using UnityEngine;
using System.Collections;

public class ray : MonoBehaviour {

public float howFar;
public Vector3 loaction;
public Transform spot_position;
public Vector3 loaction_air;

void Start() {

}

void FixedUpdate()  {
    Vector3 fwd = transform.TransformDirection(Vector3.forward);
    RaycastHit hit;

    if (Physics.Raycast(transform.position, fwd, out hit, 100)) {
        print("Ray hit something !");
        loaction = hit.point;
        howFar = hit.distance;
        spot_position.transform.position = hit.point;
    }
    else {
  //            howFar = ....
 //         spot_position.transform.position = ...
        print (" Nothing ");
    }

    loaction_air = new Vector3(spot_position.transform.position.x,spot_position.transform.position.y,spot_position.transform.position.z);
}

}


texts:
I'm looking for a way to check if a thread accessing a namespace function has a OpenGL context attached to it. I have looked around and all I can find is,

GLFWwindow* glfwGetCurrentContext();

Which will return NULL if there is no context, but is there a better way?

I'm using OpenGL 4.5 and GLFW 3.2


texts: Why are pyglet.image and texture so heavy?

texts:
Envrionment:

python: 3.6.6
pyglet: 1.3.2

Here is my code and results:

import pyglet

images = []
textures = []

with_textures = True
count = 10
for x in range(count):
    image = pyglet.image.load("big.png")  # 2.1 Mb source 2400*2400px
    images.append(image)
    if with_textures:
        texture_grid = pyglet.image.ImageGrid(image, 10, 10).get_texture_sequence()
        textures.append(texture_grid)

# RES in htop result without textures
# count = 10 - 300Mb
# count = 20 - 553Mb
# count = 30 - 753Mb
# count = 40 - 973Mb
# ~23Mb just for each Image

# RES in htop result with textures
# count = 10 - 996Mb
# count = 20 - 1878Mb
# count = 30 - 2716Mb
# count = 40 - 3597Mb
# ~86Mb for Image and prepared grid

input("Press enter to exit")

Questions:

Why each 2.1Mb file leads to 23Mb of memory usage with pyglet.image.AbstractImage?

If ImageGrid is used for creating sprite sheet -> it leads to additional ~60Mb

How to deal with it? Because if game contains 50+ big sprites it would be not real to dedicate such many memory only for textures.
Maybe there is some other approach in creating games which is used sprites? Or I should change my stack technology(pyglet as main library, also was trying with pygame) for client side?

PS: First time I've rewritten my application from pygame to pyglet, because I didn't consider some aspects of event loop in pygame, and now I hadn't test resource usage of pyglet library for my use-cases.

Update/clarification:

I'm using ImageGrid as for 3d part in vertices as for 2d part in pyglet.sprite.Sprite

Example of using in 3D part:

# texture_group is created once for each sprite sheet, same as texture_grid
texture_group = pyglet.graphics.TextureGroup(texture_grid, order_group)
...

tex_map = texture_grid[self.texture_grid_index].texture.tex_coords
tex_coords = ('t3f', tex_map)
self.entity = self.batch.add(
    4, pyglet.gl.GL_QUADS,
    texture_group,
    ('v3f', (x, y, z,
             x_, y, z,
             x_, y_, z,
             x, y_, z)
     ),
    tex_coords)

Example of using in 2D part:

pyglet.sprite.Sprite(img=texture_grid[self.texture_grid_index], x=0, y=0,
                     batch=self.batch, group=some_order_group)

Update #2:

As I figure out, allowed sizes for using pyglet.image.CompressedImageData is:

1 True
2 True
4 True
8 True
16 True
32 True
64 True
128 True
256 True
512 True
1024 True
2048 True
4096 True

But can't get texture from CompressedImageData:

big = pyglet.image.load("big.png")  # 2048*2048
compressed_format = pyglet.graphics.GL_COMPRESSED_ALPHA
compressed_image = pyglet.image.CompressedImageData(
    big.width, big.height, compressed_format, big.data)
compressed_image.texture  # exception GLException: b'invalid enumerant'

Tried with all possible GL_COMPRESS in pyglet:

allowed_formats = [x for x in dir(pyglet.graphics) if "GL_COMPRESSED_" in x]
big = pyglet.image.load("big.png")  # 2048*2048
for form in allowed_formats:
    compressed_image = pyglet.image.CompressedImageData(
        big.width, big.height, form, big.data)
    try:
        compressed_image.texture
        print("positive:", form)  # 0 positive prints
    except Exception:
        pass


texts: How to implement a professional fighting game input buffer?

texts:
Ok guys, I understand how to make a basic input buffer.

Here is my code:

public class InputBuffer : MonoBehaviour {

    public int max_buffer;
    public enum keys { down, up, left, right, X, Y, Z, A, B, C }
    public List<keys> InputPlayer;
    public enum Special { WPunch, MPunch, SPunch, WKick, MKick, SKick, Hadouken, Shoryuken }
    public List<Special> SpecialsPlayer;

    void Start () {
        InputPlayer = new List<keys>();
        SpecialsPlayer = new List<Special>();
    }

    void AddKey(keys key)
    {
        InputPlayer.Add(key);

        if (InputPlayer.Count > max_buffer)
        {
            InputPlayer.RemoveAt(0);
        }
    }

    void CheckSpecial()
    {
        if (InputPlayer[InputPlayer.Count-1] == keys.A)
        {
            if (InputPlayer[InputPlayer.Count-2] == keys.right)
            {
                if (InputPlayer[InputPlayer.Count-3] == keys.down)
                {
                    SpecialsPlayer.Add(Special.Hadouken);
                }
            }
        }
    }
}

This works really well, but then I get repeated keys in the buffer when I keep a key pressed.

I could fix it by having a last keypressed variable and then only calling the inputbuffer.getkey if the key pressed is diferent. But this makes the buffer to behave rather stiff.

I would love to see how can I improve my code so It doesn't recognizes multiples keys when a button is kept pressed, but also allow for charge moves (Guile's sonic boom).

I also would love to see how input shortcuts works (using a previous special command as part of a second one, usually used in cancels to supers).

I would love to see what's the proper way to handle input buffers in kof and SF.


texts: Blending semi-transparent images while not stacking their alphas

texts:
In libgdx/OpenGL ES I want to render multiple semitransparent textures while keeping the alpha still semi transparent. For example If I render a 0.5 alpha circle on top of another 0.5 alpha circle, alpha should remain 0.5, output alpha should be maximum value of input alpha and destination alpha.

I looked a bit, it looks like glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX) should do the trick, but it is not GL_MAX operator is not available for OpenGL ES. Weirdly, it works when I use integer value for (0x8008) but I guess I can't trust that :D

How can I achieve such an effect?


texts: How can I open source my Unity project when I use third party assets?

texts:
I know you are not allowed to open source a Unity project that contains asset store items that are either paid or under the default license. I am just wondering if there's any way to make my git repository public without getting into trouble.

Would it be possible to compile all third party assets into binary and keep the rest of the project text only? Would this solve the redistribution problem of third party assets while still keeping my own code and assets open source?

I know about just adding a list of required assets, but I'm looking for a better approach: a way to just download the repository, import it and it just works. If this is at all possible please share your solutions.


texts: If I convert my LibGDX game to an exe, is it legal?

texts:
I have a LibGDX jar file, and I want to have it as an EXE. Would that be legal? (Using launch4j)

Also, how do I obfuscate a LibGDX game?


texts: How to detect when the player has filled a shape?

texts:
In my game, the player is presented with a plane containing obstacles (orange / blue) and regions of empty space (white).

The player moves their green cube around the empty space, which instantiates a trail of green cubes behind it, painting the path they've travelled.

I need to detect when the player has painted all of the empty space, so that they can proceed to the next level.

Initial state of the board:

When the player has painted all of the empty space:

Currently I store my instantiated paint objects in a list.

But I don't know how to check that the objects in this list cover all of the empty space. How can I do that?

public float speed = 10f;
private RaycastHit hit;
public GameObject paintcube;
float maxdistance = 0.51f;
bool moves;

private void FixedUpdate()
{
    Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 3, Color.green);
    if (Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward), out hit, maxdistance/*,layerMask*/))
    {
         if (hit.collider.gameObject.tag == "myobstacle")
         {
             moves = false;
         }
         if(moves)
         {
             movepaint();
         }
     }
}

public void movepaint()
{
     if (moves)
     {
         MyList.Add( Instantiate<GameObject>(paintcube, position, transform.rotation) );
     }
}


texts:
Until now, I have been using a vertexData structure to store data for a Vertex Buffer Object (VBO); vertexData holds a static array of 6 vertices (2 triangles). I then save them to a vector of the vertexData type, before finally using this vertexData in the buffering method:

struct vertexData {

    Vertex vertices[6]; // position, color, UVs
};

std::vector<vertexData> _DATA;

void SpriteBatch::createVBO() {

    glBindBuffer(GL_ARRAY_BUFFER,_VBO);

    glBufferData(GL_ARRAY_BUFFER,_DATA.size()*sizeof(vertexData),nullptr,GL_DYNAMIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER,0,_DATA.size()*sizeof(vertexData),_DATA.data());

    glBindBuffer(GL_ARRAY_BUFFER,0);
}

This works good, as everything in my vector is contiguous. However, I want to work with other vertex sizes, for different shapes. I tried a vector of vector types, in oder to  work with dynamically allocated arrays, but it did not work, as it was not contiguous.

At first, I thought about using a polymorphic class to be stored as a vector, where every child would have a different array size; but then I recognized that this vertex buffer does not work with pointers

The second idea was to create a generic SpriteBatch. For example, a batch for 6 vertices, and then a batch for 2 vertices, etc. etc.

What is the best way to store Vertex Buffer Object data?


texts: What is the easiest and shortest way to draw a 2d line in c/c++?

texts:
I am fairly new to c/c++ but I do have experiance with directx and opengl with java and c#. My goal is to create a 2d game in c with under 2 pages of code. Most of what I have seen requires 3 pages of code to just get a window running.

I would like to know the shortest code to get a window running where I can draw lines. I believe this can be done in less lines with opengl versus directx. Is there maybe an api or framework i can use to shorten it more?

Also, it would be nice if the solution were cross platform compatible.


texts: Is there an existing algorithm to find suitable locations to place a town on a heightmap?

texts:
I've been experimenting with random generation of a "map" with the intention of building a basic sort of procedural map generator. Generating a reasonable heightmap using libnoise hasn't been that much of an issue.

I am considering using A* or similar to plot two main "roads" across the terrain from top to bottom and left to right, intersecting in the middle of a town in some relatively flat section of the terrain.

I am unsure of the best way to go about locating the optimal point to place the town though. I created a "steepness" map as another map which looks at the points surrounding each point on the heightmap to determine the steepness and then sets 1 if steep and 0 if not to create a "mask" of steep and flat areas.

How then could I determine the largest rectangle area that will fit within those flat areas?

Or perhaps I need to re-look at this a different way and place the "town" first then build the terrain around it rather than trying to place it into an existing terrain.


texts: How to use GdxAI with libgdx ashley ecs framework?

texts:
I'm planning to use GdxAI Telegraph in GdxAshley ecs framework, my problem is how I'm gonna create a telegraph component if I wanted to dispatch a message? I have created AIComponent and AISystem.

class AIComponent implements Component{
    StateMachine<Entity, EntityState> fsm;
}

class AISystem extends IteratingSystem {

    public void processEntity(Entity entity, float deltaTime) {
         AIComponent ai = Mappers.ai.get(entity);

         ai.fsm.update();
    }

}

For example I wanted to dispatch a message using space input.

if(Gdx.input.isTouched()) {

     MessageManager.getInstance().dispatchMessage(
                0.0f, // no delay
                entitySender, entityReceiver,
                MessageType.SAYHELLO, null);

}

I'm thinking of creating a class that extends Entity and implement it to Telegraph. But the ashley ECS approach will be disregard here.

class EntityAI extends Entity implements Telegraph {

     StateManager fsm;

     public EntityAI (StateManager fsm) {
          this.fsm = fsm;
     }

     @Override
     public boolean handleMessage(Telegram telegram) {
         return fsm.handleMessage(telegram); // In this part, the logic exists. Im thinking of creating a System that will handle message? but how
     }

}

Question How do I properly convert the this EntityAI to entity-componentbased-system approach? In the below code is not tested but it was the idea entered my mind.

class Script implements Telegraph {

     StateManager fsm;

     public Script (StateManager fsm) {
          this.fsm = fsm;
     }

     @Override
     public boolean handleMessage(Telegram telegram) {
         return fsm.handleMessage(telegram);
     }
}

class ScriptComponent implements Component {
     Script script;
}

 ScriptComponent script
 AIComponent ai
 ai.fsm = new StateMachine();
 script.script = new Script(ai.fsm); // as you can see here the fsm is used twice in component

 // AIComponent has StateMachine
 // ScriptComponent need StatMachine
 // do you in the above code is a good idea?

MessageManager.getInstance().dispatchMessage(
                0.0f, // no delay
                scriptSendeer, scriptReceiver,
                MessageType.SAYHELLO, null);


texts: How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction?

texts:
Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead.

It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre-existing momentum will carry it wildly off-course, and not straight toward PointB.

It could turn exactly 180° around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions.
It would be more efficient to turn and start accelerating in some specific direction that will bleed off the unnecessary momentum but keep any useful momentum, course-correcting so that it is now moving toward PointB.

I'm trying to figure out how to calculate that "specific direction" that the rocket needs to start accelerating toward, in order to efficiently reach PointB. I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed.
Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc.
Can anyone help me out?


texts: Can someone explain this occurrence with a fbx model in xna?

texts:
Because this is kind of weird to explain, let's show you what I mean.  This is in my game.  When I import this base ship model, it should be at (1000,1000,1000), but the model acts like it's at (1000,1000, 0).  Note it is positioned correctly when I use a .x model.  So it has to be the model.  I need to know what's wrong with it.

Here is the model file, tell me if anything is wrong with it: https://dl.dropbox.com/u/92848165/station2.FBX

http://i.imgur.com/VsjH8.jpg

EDIT: The model works if you import it into Google Sketchup...but you lose the textures, not very nice.


texts: Portal 2 mapping dimensions and measurments

texts:
I am wanting to start building a portal 2 map for single player mode.

I have used the hammer world editor before but not for portal.

As far as portals are concerned will the distance I drop vertically be equal to the distance I am thrown horizontally?

So a 16 unit drop throws me 16 units forward?


texts: How AAA games use this texture in the tone-mapping shader?

texts:
I found that Battlefield 3 as well as Saint's Row the Third use this texture in their final tone-mapping stage. Can anyone share a link to an article about how this texture is used?

UPDATE: As there are hardly any examples of Color Grading implementation on the net, I will post my quick and dirty sample for XNA 4.0. This does nothing but builds the default 2d colormap from scratch on GPU, copies it's contents into a 3d texture on CPU and performs the actual color-correction with the shader code from the article provided in the answer.
XNA 4.0 Color Correction Sample
If you want to know what you can do with this, look here:
http://the-witness.net/news/2012/08/fun-with-in-engine-color-grading/
In short the author explains there, how you can basically make a screenshot of your normal in-game image with the default color grading palette on top, perform screenshot color correction in photoshop, cut and copy the deformed color correction palette into the engine and have that color correction applied for every in-game scene automatically.


texts: How can a one-man team create game audio?

texts:
I am basically a 14 years game programmer.
I am using Unreal Engine 4.

I can't make a game without 3D models.
So , I started to learn how to draw (for reference images) and how to make some 3D models.
I am using Corel Painter and Blender.

I can't make a game without audio.
This is a much larger problem than the models' one.
There aren't high quality (or even low quality) tutorials that can teach you "How to make music for your game" or "How to make sound effects for your game"

I made a topic on Unity forums and they suggested to me to hire someone who can create the audio for me but I really want to make everything myself as the game I'm working on will not be published, it's just a 'showcase' for my programming 'skills'.

So, I need a program and maybe a MIDI controller that is user friendly like Ableton Push, for example, that I can use to create sound effects for my game like explosions, fire, engines' sound, ... etc. The Music isn't a much of a problem as I can use something like MAGIX Music Maker as it has user friendly interface and can create some really good music.

Thanks in Advance


texts:
I am trying to read in from 2 text files (one contains the start and end coordinates, the other is a map of costs for use with the Manhatten Distance) and I'm really struggling with the implementation of the code from various algorithms I've found.

I've been able to read in the text files and put them into 2 separate arrays fine, the real issue I'm having is with adding to the open list and compares their costs so that the smallest goes onto the priority queue and then compare its neighbors, I just cannot work this out after hours upon hours of reading and watching YouTube videos on the subject, any help?

Here is my code so far:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <deque>
#include <math.h>
#include <vector>
#include <deque>
using namespace std;

struct pNode
{
    int xPos;
    int yPos;
    pNode* Parent;
    pNode* child;

    float g; //Cost of this Node plus predecessors
    float h;//Heuristic estimate to Goal state
    float f; // f= g+h

    pNode() :
        Parent(0),
        child(0),
        g(0.0f),
        h(0.0f),
        f(0.0f)
    {
        bool wall = false;
        bool water = false;
        bool grass = false;
        bool startNode = false;
        bool endNode = false;
    }
};

class compare
{
public:

    bool compareNodes()
    {
        pNode *x;
        pNode *y;
        return x->f > y->f;
    }
};

class dMap
{
public:
    static const int ARRAY_SIZE = 100;

    void LoadFile();
    void Display() const;
    void priorityQueue();
    void aStar();

private:
    pNode   mArray[ARRAY_SIZE];
    pNode   mArrayCoords[ARRAY_SIZE];
};

void dMap::LoadFile()
{
    ifstream infile("dMap.txt");
    if (!infile)
    {
        cout << "Cannot open File";
        exit(1);
    }
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        infile >> mArray[i].xPos >> mArray[i].yPos;
    }
}

void dMap::priorityQueue()
{
    int disX = mArray[ARRAY_SIZE].xPos;
    int disY = mArray[ARRAY_SIZE].yPos;
    int heuristic(int xPos, int yPos);

    struct pQueue
    {

        int fx;
        int fy;
        int x;
        int y;

        int cost;
        int h;
        int totalCost;

        pQueue(int _x, int _y, int _cost)
        {
            x = _x;
            y = _y;
            cost = _cost;
            h = heuristic(x, y);

            totalCost = cost + h;
        }

        int manhattenDistance(int xPos, int yPos)
        {
            return abs(xPos - fx) + abs(yPos - fy);
        }//Manhatten Distance

        bool operator<(const pQueue &b)const
        {
            return totalCost>b.totalCost;
        }

    };
}

void dMap::aStar()
{
    LoadFile();

    pNode mArrayCoords[ARRAY_SIZE];
    ifstream infile("dCoords.txt");
    if (!infile)
    {
        cout << "Cannot open File";
        exit(1);
    }
    for (int i = 0; i <9; i++)
    {
        infile >> mArrayCoords[i].xPos >> mArrayCoords[i].yPos;
    }

    deque <pNode*> openList;
    pNode* startNode = new (pNode);
    deque <pNode*> closedList;
    pNode* endNode = new (pNode);
    pNode* currentNode = new (pNode);
    deque <pNode*> finalList;

    //startNode ->

}


texts: Having 3D material properties depend on shader

texts:
Disclaimer: I apologise if this is somehow a duplicate question or is unclear.

I am in the process of writing a 3D scene renderer/editor in C++ using the OpenGL specification. It is actually going surprisingly well considering my past experience (all but none) however I have hit hurdle in designing the way materials work. First, this is how they work now:

Materials have a diffuse/albedo map, a normal/bump map, and a specular map. They also have a diffuse/albedo colour, and a shininess value for when no specular map is provided. This works fine and all however I noticed Unity's material's properties depend entirely on a shader. This is pretty much what I want as this is wonderfully flexible.

I know you can get a list of a shader program's GLSL uniforms as described here but I am struggling with what my Material class should be looking like. Do I have each material hold a map of textures, colours, floats, with the keys being their GLSL uniform name? Or is there a nicer more elegant way? The reason I am against this is because I wouldn't know how to organise the properties in a GUI when all I am given is a uniform name. For example I might have multiple diffuse or specular maps, and I would like to arrange these in a specific manor.

Please let me know if this is an awful question, or if I could improve it in any way. My brain hurts right now.


texts: How to use HyperLink with Actor in Libgdx

texts:
I am making a quiz game using LibGDX. I want it to redirect to a website. I am using classes like Text and Label that extends Actor to write text using a bitmap Font. I have no idea on how to provide a link (like anchors in html) in a native app. However, I am not very good at Android but know java well. In android , I saw on stackexchange, we can do so using Intent or string.xml configuration.

Can anyone suggest me a way to do so using Actor in libGDX?


texts:
I have a top down shooter. The player can move in the primary 4 directions, and follows the mouse for rotation.

When I shoot, the bullets never leave the player, they just spawn on top of the player sprite.

I have tried a combination of velocity and AddForce methods, but I don't understand why the bullets never move. I have tried moving them in the Bullet's script or in the calling WeaponAttack script that Instantiates the Bullet.

Side note for educational purposes: Which method is better? Should the bullet govern its direction and velocity or should the Instantiating class govern it?

PLAYER ROTATION SCRIPT

public class RotateToDirection : MonoBehaviour {

    Vector3 mousePos;
    Camera cam;
    Rigidbody2D rid;

    void Awake () {
        rid = this.GetComponent <Rigidbody2D> ();
        cam = Camera.main;
    }

    void FixedUpdate () {
        rotateToDirection ();
    }

    private void rotateToDirection() {
        mousePos = cam.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z - cam.transform.position.z));
        rid.transform.eulerAngles = new Vector3 (0, 0, Mathf.Atan2 ((mousePos.y - transform.position.y), (mousePos.x - transform.position.x)) * Mathf.Rad2Deg);
    }
}

WEAPONATTACK (SHOOTS THE BULLET)

public class WeaponAttack : MonoBehaviour {
    public GameObject bullet;
    public GameObject player;

    public float bulletSpeed;

    void FixedUpdate () {
        if(Input.GetMouseButton (0)){
            attack ();
        }

    }

    public void attack(){
        Instantiate (bullet, player.transform.position, player.transform.rotation );
        //Rigidbody2D bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0, 0, 1))) as Rigidbody2D;
        //bulletInstance.velocity = transform.forward * bulletSpeed;

        Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(),  player.GetComponent<Collider2D>());

    }

}

BULLET

public class Bullet : MonoBehaviour {

    public float moveSpeed = 500.0f;
    private float killTime = 1.0f;
    private Rigidbody2D body;

    void Awake() {
        body = GetComponent<Rigidbody2D> ();
    }

    void FixedUpdate(){
        killTime -= Time.deltaTime;
        if (killTime <= 0) {
            Destroy (this.gameObject);
        } else {
            body.position = body.position * moveSpeed * Time.deltaTime;
        }
    }

}


texts: New way of integrating Openfeint in Cocos2d-x 0.12.0

texts:
I am trying to implement OpenFeint for Android in my cocos2d-x project. My approach so far has been creating a button that calls a static java method in class Bridge using jnihelper functions (jnihelper only accepts statics).

Bridge has one singleton attribute of type OFAndroid, that is the class dynamically calling the Openfeint Api methods, and every method in the bridge just forwards it to the OFAndroid object.

What I am trying to do now is to initialize the openfeint libraries in the main java class that is the one calling the static C++ libraries. My problem right now is that the initializing function

void com.openfeint.api.OpenFeint.initialize(Context ctx, OpenFeintSettings settings, OpenFeintDelegate delegate)

is not accepting the context parameter that I am giving him, which is a "this" reference to the main class. Main class extends from Cocos2dxActivity but I don't have any other that extends from Application.

Any suggestions on fixing it or how to improve the architecture?

EDIT:

I am trying a new solution. Make the bridge class into an Application child, is called from Main object, initializes OpenFeint when created and it can call the OpenFeint functions instead of needing an additional class.

The problem is I still get the error.

03-30 14:39:22.661: E/AndroidRuntime(9029): Caused by: java.lang.NullPointerException
03-30 14:39:22.661: E/AndroidRuntime(9029):     at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:85)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.internal.OpenFeintInternal.validateManifest(OpenFeintInternal.java:885)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.internal.OpenFeintInternal.initializeWithoutLoggingIn(OpenFeintInternal.java:829)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.internal.OpenFeintInternal.initialize(OpenFeintInternal.java:852)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.api.OpenFeint.initialize(OpenFeint.java:47)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at nurogames.fastfish.NuroFeint.onCreate(NuroFeint.java:23)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at nurogames.fastfish.FastFish.onCreate(FastFish.java:47)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)


texts: How to access Collider in c# script with its tag name

texts:
I want to access a Collider in c# script file with its tag name
I Tried this

if (Collider2D == Physics2D.OverlapPoint(touchPos))
{
    Some Code to be Performed
}

I want to access this Collider2D with its Tag Name like this

if (GameObject.FindGameObjectWithTag("tag name") == Physics2D.OverlapPoint(touchPos))
{
    Some Code to be Performed
}

But Its not working
Please Help...

public GameObject[] targets,targetss;

    void Start () {
        targets = GameObject.FindGameObjectsWithTag ("right screen");
        targetss = GameObject.FindGameObjectsWithTag ("left screen");
    }

    void Update () {
        if (Input.touches.Length <= 0) {

        } else {
            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(wp.x, wp.y);

            foreach(GameObject target in targets)
            {
                if (target.collider2D == Physics2D.OverlapPoint(touchPos))
                {

                    GameObject.FindGameObjectWithTag("player2").transform.position =
                    new Vector2(GameObject.FindGameObjectWithTag("player2").transform.position.x, wp.y);

                }
            }

            foreach(GameObject target in targetss)
            {
                if (target.collider2D == Physics2D.OverlapPoint(touchPos))
                {

                    GameObject.FindGameObjectWithTag("player1").transform.position =
                    new Vector2(GameObject.FindGameObjectWithTag("player1").transform.position.x, wp.y);

                }
            }

        }
    }