texts: Why is Unity 2D Alpha-Blurring my pixel sprite?

texts:
So I have just brought in a place holder block for the ground in unity 2D, and it's 16 by 16 pixel image, and for some reason unity is automatically blurring the image. So I was wondering if there was any way to stop unity from automatically blurring the image. I would really appreciate if someone could tell me how to stop the image form being blurred. Also sorry if this is, just something that is incredibly simple to fix, I just started using unity 2D instead of 3D so it's different for me.

Thanks, Nova


texts: What is the math behind rendering isometric with the aid of Depth Maps?

texts:
I am currently in the process of designing an Isometric game, and one of the features we are trying to add, is using sprite depth maps to render geometry in the correct order.

The reason we are trying to do this, is a number of our game objects make use of overlapping sprites, and the animation is not always in sync with it's other parts.

I do have experience with working in 3D. But the issue comes to using something that is normally generated on the fly, pre baking it, and then retrofitting it to work with what ever distance.

So... something similar to what the sims has done with it's objects.

Linky


texts: How should I render multiple objects in OpenGL?

texts:
I am just getting my head wrapped around modern OpenGL. Let's say that I would like to draw 10 objects, how would I structure that? Would I call glDrawElements(...) in a for loop 10 times?

void render() {
  shader.bind(); // calls glUseProgram
  bindVAO();     // calls glBindVertexArray

  for(int i = 0; i < 10; i++) {
    glDrawElements(....)
  }

  unbindVAO;
  shader.unbind();
}


texts: How to find objects in front of my player

texts:
I am trying to find an object that is in front of my player sprite using the following code

RaycastHit2D hit = Physics2D.Raycast(transform.position,Vector2.right,EnemyLayer);
//EnemyLayer is the layer having enemy
if(hit!=null){
print (hit.collider.tag);

}

But this is printing "player",the tag of the object on which the script is attached.What am i doing wrong?
EDIT: Ok,I found out why it was printing player-because I had a big circular collider surrounding my player. Deactivating it gives me the following error

NullReferenceException: Object reference not set to an instance of an object

I have no clue what it means. Any help is appreciated.


texts:
I'm trying to embed music in my XNA game's .exe (with resources) but compiling them as a sound effect stores the music in uncompressed form, which results in a 16 MB .exe.

I can compress my music with wma, and compile it as a song, which unfortunately (in my case) leaves the music as a plain .wma file.

Basically, I want a single standalone .exe, with my content stored as resources. If I could compile a wma song to a single .xnb content file, I could embed that file. I don't know how to do that without uncompressing the music. It might be possible to keep the wma file separate and store it in the resources, but I haven't figured out how to get the .xnb content file to work with it.

In order of preference:

Can I compile a wma to a xnb without decompressing it?
Can I store the wma in the exe resources and load it into a song?
Is there any other way to decrease the size of an exe with embedded music?

EDIT: The comments mentioned using XACT. This seems like a good solution. I have another question. Since the XACT sounds are not loaded with Content.Load, it will not automatically look in the application resources (I have Content set up to do so). Is there a way to load XACT sounds from resources? If not, I will accept having to load content from separate files.


texts:
Possible Duplicate:
  How to choose how to store data?

The game I'm designing will be mainly written in a high level scripting language (leaning towards either Lua or Squirrel) with a C++ core.  In addition to scripts I'm also going to need different data files.  Many data files will be for static information such as graphical assets and monster types.  I'd also want to create and update data files at runtime for user information like option settings and game saves.

Can I get away with using plain script files (i.e. .lua or .nut files) for my data files, or is it better to use dedicated markup formats like XML or YAML?

If I use script files, loaded separately from my true scripts, then I wouldn't need an extra library to read those files.  Scripting languages like Lua also have table syntax that lend themselves towards data definition.  On the other hand I'd have to write my own schema check code.  These languages also don't seem to support serialization "out of the box" like the markup format libraries do.


texts: When should I load assets for optimal performance?

texts:
I'm writing a game using LWJGL and Java, and was wondering if there were best practices for when to load resources.

I have seen examples that load all resources when initializing the game (XNA), ones that load the new resources needed for each level while referencing the already loaded assets again.


texts: Do we have events for +/- buttons for a serialized list?

texts: Does Unity fire any events when the user clicks these buttons? Or is there a way how to hook up code to respond to these actions?


texts:
I'm trying to use Skins with TextButtons. However I'm having an issue where the TextureRegions of the Skin are NOT being scaled down to the tablesize.

This is leading to an issue like in this image:

As you can see that is the e from the word Hello. I managed to scale that down to a more reasonable size (still wrong). However the Button textures are still way too large.

Any ideas? Because I am pulling my hair out. I am using a custom viewport with a custom screenspace width and height. Here is the create method for the menu.

    public void create(){
    menuStage = new Stage();
    camera = new OrthographicCamera();
    viewPort = new StretchViewport(SCREEN_SPACE_WIDTH, SCREEN_SPACE_HEIGHT, camera);
    viewPort.setWorldSize(SCREEN_SPACE_WIDTH, SCREEN_SPACE_HEIGHT);
    menuStage.setViewport(viewPort);

    devTexture = new Sprite (new Texture(Gdx.files.internal("data/16by9.png"), true));

    Image newActor = new Image(devTexture.getTexture());
    newActor.setSize(
            viewPort.getWorldWidth(),
            viewPort.getWorldHeight()
    );

    menuStage.addActor(newActor);
    skin = new Skin(Gdx.files.internal("data/uiskin.json"));

    menuTable = new Table();

    skin.getFont("default-font").setScale(0.08f);

    menuTable.debugAll();

    menuTable.setFillParent(true);
    TextButton a,b,c;

    a = new TextButton("hello", skin);
    b = new TextButton("hello", skin);
    c = new TextButton("hello", skin);

    a.getStyle().up.setMinWidth(2.0f);

    b.getStyle().up.setMinHeight(2.0f);
    b.getStyle().up.setMinWidth(2.0f);

    c.getStyle().up.setMinHeight(2.0f);
    c.getStyle().up.setMinWidth(2.0f);

    menuTable.row();
    menuTable.add(a).size(2.0f, 1.0f);
    menuTable.add(b).size(2.0f, 1.0f);
    menuTable.add(c).size(2.0f, 1.0f);

    menuStage.addActor(menuTable);

    camera.translate(
            newActor.getWidth() / 2,
            newActor.getHeight() / 2
    );
}


texts:
I'm basically trying to understand the chronology/sequence of the algorithm and where should I call the
scoring mechanism function that calculates the score of each move and returns an int.
For example, this code is an implementation of the Minimax algorithm in the Tic-Tac-Toe game:
function bestMove() {
// AI to make its turn
let bestScore = -Infinity;
let move;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
  // Is the spot available?
  if (board[i][j] == '') {
    board[i][j] = ai;
    let score = minimax(board, 0, false);
    board[i][j] = '';
    if (score > bestScore) {
      bestScore = score;
      move = { i, j };
    }
  }
}
}
board[move.i][move.j] = ai;
currentPlayer = human;
}

let scores = {
X: 10,
O: -10,
tie: 0
};

  function minimax(board, depth, isMaximizing) {
  let result = checkWinner();
  if (result !== null) {
  return scores[result];
  }

  if (isMaximizing) {
  let bestScore = -Infinity;
  for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    // Is the spot available?
    if (board[i][j] == '') {
      board[i][j] = ai;
      let score = minimax(board, depth + 1, false);
      board[i][j] = '';
      bestScore = max(score, bestScore);
    }
  }
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    // Is the spot available?
    if (board[i][j] == '') {
      board[i][j] = human;
      let score = minimax(board, depth + 1, true);
      board[i][j] = '';
      bestScore = min(score, bestScore);
    }
  }
}
return bestScore;
}
}

The only implementation of the scoring mechanism is when the board identifies a win situation for one of the players.
In complex games there are too many combinations so the depth will be restricted to let's say 3.
the scoring mechanism needs to be called for each "move" that is being examined, otherwise we will get back 0 for each move, and the algorithm will just go for the next open spot,
since the depth doesn't reach a possible wining series of moves.
If I planned a scoring mechanism function that compensate and "punishes" each move (for every i,j) minimax goes through and returns an int (the score), how should I fit it correctly in the algorithm?
It sounds simple but honestly nothing makes sense to me at this point...
P.S
My game is pretty complex to explain and would take a long time,
therefore, I'm looking for the more logic answer so I can implement it myself.
Thanks in advance,
Omer


texts: SpriteKit tunneling when user moves node

texts:
I have a question about (continuous) SpriteKit collision detection.
I have a SwiftUI/SpriteKit project in which balls fall from above and the user tries to catch the balls with a cup.
The user moves the cup horizontally by dragging their finger.
The physics work well with one exception -- the balls properly collide with each other, and with the cup, except when the cup is being moved.
When the cup is being moved by the user, the balls that had fallen into the cup tunnel right through the side of the cup.
Again, the balls collide with the cup correctly, and settle in the cup, except when the cup is moving.
The collision types:
enum CollisionTypes: UInt32 {
    case ball = 1
    case cup = 2
}

The cup:
func cup() -> SKSpriteNode {
        let screenSize = UIScreen.main.bounds
        let cupNode = SKSpriteNode(imageNamed: "cup2.png")
        let cupOutline = SKSpriteNode(imageNamed: "cupOutline.png")

        cupNode.position = CGPoint(x: screenSize.width*0.5, y: MainData.cupY)
        cupNode.size = CGSize(width: screenSize.width * 0.25, height: screenSize.width * 0.35)
        cupNode.name = "cup"
        cupNode.zPosition = 1.0

        cupNode.physicsBody = SKPhysicsBody(texture: cupOutline.texture!, size: CGSize(width: screenSize.width * 0.25, height: screenSize.width * 0.35))
        cupNode.physicsBody?.isDynamic = false
        cupNode.physicsBody?.usesPreciseCollisionDetection = true
        cupNode.physicsBody?.categoryBitMask = CollisionTypes.cup.rawValue
        cupNode.physicsBody?.collisionBitMask = CollisionTypes.ball.rawValue

        return cupNode
    }

The balls:
func initializeBalls(screenWidth: CGFloat, screenHeight: CGFloat) {
        for i in 0..<numOfBalls {
            let radius = screenWidth * 0.02
            let x = screenWidth * CGFloat.random(in: 0...1)
            let y = screenHeight
            let ballNode = SKSpriteNode(imageNamed: "ball.png")

            ballNode.position = CGPoint(x: x, y: y)
            ballNode.size = CGSize(width: radius*2, height: radius*2)
            ballNode.name = "ball\(i)"

            ballNode.physicsBody = SKPhysicsBody(circleOfRadius: radius)
            ballNode.physicsBody?.usesPreciseCollisionDetection = true
            ballNode.physicsBody?.mass = 5.0
            ballNode.physicsBody?.isDynamic = true

            ballNode.physicsBody?.categoryBitMask = CollisionTypes.ball.rawValue
            ballNode.physicsBody?.collisionBitMask = CollisionTypes.cup.rawValue

            ballNode.physicsBody!.contactTestBitMask = ballNode.physicsBody!.collisionBitMask

            ballNode.physicsBody?.restitution = 0.1
        }
    }

Here's how I move the cup, in my GameScene:
func touchMoved(toPoint pos : CGPoint) {
     let action = SKAction.move(to: CGPoint(x: pos.x, y: MainData.cupY), duration: 0)

     cupNode?.run(action)
}

Why is this tunneling happening, and how do I avoid it?


texts: How can I send Android notifications from my Unity game?

texts: I'm want to send local notification on Android with Unity3D but I don't know how to do it. Any suggestions?


texts: How to access a prefab's boolean property through collision (with the same Prefab but different Instance)?

texts:
I am a trying to recreate the first stage of Super Mario Brothers, but I am having a bit of trouble with the collision system between Koopa Shells. I have written two different scripts in hopes to achieve this:

This First script is to handle the Basic movement and start shell movement on Player Collision

It's Rather long so I took the liberty of including only parts that were in direct correlation/ causation of the problem

     public class KoopaShell : MonoBehaviour
     {
         //Makes this accessible to other Scripts
         public bool Moving;

         // Boolean Flags to be inherited
         bool shellLeft, shellRight, rightBlocked, leftBlocked;
         public float rayDis;
         public LayerMask enemyMask;
         public Transform rCast;

 [... Rest of the code..]
         void OnCollisionEnter2D(Collision2D coll)
         {
             if (leftBlocked || rightBlocked) // If the either side of the shell is hit
                 if (coll.gameObject.tag == "Player" && Moving == false) // If the player makes contact with a resting shell
                 {
                     MoveShell();
                 }
         }

         public IEnumerator MoveShell() //Courotine for 2D Collision
         {
                     //The Courotine will wait for the end of the frame
                     yield return new WaitForFixedUpdate();
                     //Then set moving to true
                     Moving = true;
         }
     }

The Second Script handles all other collision and inherits from the first in an attempt to simplify the calling from script to script.... Could also be the cause of my problem.

public class MovingShellScript : KoopaShell
{

//This is a continuation of the KoopaShell Script
//Dealing with 2D Collision

void OnCollisionEnter2D(Collision2D col)
{
   if (col.gameObject.tag == "Koopa Shell") //  if contact is made with another shell that is moving
     if(col.gameObject.Equals(Moving) == false) //if the shell is not moving
     {
      {
          Destroy(col.gameObject);  // Then the resting shell is destroyed
          Debug.Log("Looks like another shell is unemployed");
       }
     }

    if (col.gameObject.tag == "Enemy") // If a Enemy is hit by the Shell
       if (Moving == true) // and If the Shell is moving
       {
                     // The GameObject hit is Destroyed
                     Destroy(col.gameObject);
       }
     }
 }

Currently the script above does not destroy the various gameobjects under the Enemy and Player tag. Maybe this could be done implicitly with an associated script to the desired gameobject that correlates with the tag....

Also the script destroys both shells during a collision. I don't understand why my various boolean flags aren't creating the desired result(s)

If both shells are moving then both shells are destroyed.
If only one shell is moving then the resting shell is destroyed.

I am seeking to understand the error in my logic for this to work as desired.

Thank you for your time!


texts: I'm making an Angry Birds like game and I need to limit the distance that the user can pull back the slingshot, how do I do this?


texts: How can I render a semi transparent model with OpenGL correctly?

texts:
I'm using OpenGL ES 2 and I want to render a simple model with some level of transparency. I'm just starting out with shaders, and I wrote a simple diffuse shader for the model without any issues but I don't know how to add transparency to it. I tried to set my fragment shader's output (gl_FragColor) to a non opaque alpha value but the results weren't too great. It sort of works, but it looks like certain model triangles are only rendered based on the camera position... It's really hard to describe what's wrong so please watch this short video I recorded:

http://www.youtube.com/watch?v=s0JqA0rZabE

I thought this was a depth testing issue so I tried playing around with enabling/disabling depth testing and back face culling. Enabling back face culling changes the output slightly but the problem in the video is still there. Enabling/disabling depth testing doesn't seem to do anything.

Could anyone explain what I'm seeing and how I can add some simple transparency to my model with the shader? I'm not looking for advanced order independent transparency implementations.

edit:

Vertex Shader:
// color varying for fragment shader
varying mediump vec3 LightIntensity;
varying highp vec3 VertexInModelSpace;

void main()
{
    //
    vec4 LightPosition = vec4(0.0, 0.0, 0.0, 1.0);
    vec3 LightColor = vec3(1.0, 1.0, 1.0);
    vec3 DiffuseColor = vec3(1.0, 0.25, 0.0);

    // find the vector from the given vertex to the light source
    vec4 vertexInWorldSpace = gl_ModelViewMatrix * vec4(gl_Vertex);
    vec3 normalInWorldSpace = normalize(gl_NormalMatrix * gl_Normal);
    vec3 lightDirn = normalize(vec3(LightPosition-vertexInWorldSpace));

    // save vertexInWorldSpace
    VertexInModelSpace = vec3(gl_Vertex);

    // calculate light intensity
    LightIntensity = LightColor * DiffuseColor * max(dot(lightDirn,normalInWorldSpace),0.0);

    // calculate projected vertex position
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

}

Fragment Shader:
// varying to define color
varying vec3 LightIntensity;
varying vec3 VertexInModelSpace;

void main()
{
    gl_FragColor = vec4(LightIntensity,0.5);
}


texts: Can browser based games be developed without JS/Flash?

texts:
I have absolutely no knowledge about game development, and for 2 years I have been a web application developer (in PHP & JS).

I'd like to learn game development, and I'd also like to free myself from PHP and Javascript and learn some game related concepts in C/C++/C# (whatever is required for game development).

Can browser-based games be developed in a language like C/C++/C#/Python and not using Javascript or Flash? Additionally, would these be superior (in terms of graphics and browser compatibility,support) to games developed using Javascript/HTML5?

EDIT:

By browser based games I'm looking at this.
Java/Python/C++ which among these would provide a better support for browser game dev (interms of compatibility, graphics)?


texts: Automated Unity iOS command line build on Mac

texts:
I am doing the iOS builds for a group of Unity (Unity3d) game developers.

After pulling the latest git updates, I start up the Unity editor on my Mac and choose "Build Settings", select the iOS target platform, press Build, specify a destination folder and that is it.

Can this exact process be done automatically via the terminal prompt?


texts:
I'm just starting to learn Unity and I must admit at the moment im struggling linking my code scripts together. Im used to having a main class to work from.

I have been trying to implement virtual touch joysticks. I have the following code and it does control the player, but it is just moving a rigidbody.

What I want is to make this virtual joystick give out a relevant X,Y vector2 so that I can access it in another class, specifically for this case I am trying to use it with the prefab Car from the Standard Assets pack. All I am trying to do for now is if up is held, accelerate the car.

The car prefab code is not altered so far. And therefore it works if I use keyboard, but if I build for Android the touch joysticks respond to touch but I cant get the car to move.

Here is the joystick code im using:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]

public class PlayerMoveController : MonoBehaviour {

// PUBLIC
public SimpleTouchController leftController;
public SimpleTouchController rightController;
public float speedMovements = 5f;
public float speedContinuousLook = 100f;
public float speedProgressiveLook = 3000f;
public bool continuousRightController = true;

// PRIVATE
private Rigidbody _rigidbody;
private Vector3 localEulRot;
private Vector2 prevRightTouchPos;

void Awake()
{
    _rigidbody = GetComponent<Rigidbody>();
    rightController.TouchEvent += RightController_TouchEvent;
    rightController.TouchStateEvent += RightController_TouchStateEvent;
}

public bool ContinuousRightController
{
    set{continuousRightController = value;}
}

void RightController_TouchStateEvent (bool touchPresent)
{
    if(!continuousRightController)
    {
        prevRightTouchPos = Vector2.zero;
    }
}

void RightController_TouchEvent (Vector2 value)
{
    if(!continuousRightController)
    {
        Vector2 deltaValues = value - prevRightTouchPos;
        prevRightTouchPos = value;

        transform.localEulerAngles = new Vector3(transform.localEulerAngles.x - deltaValues.y * Time.deltaTime * speedProgressiveLook,
            transform.localEulerAngles.y + deltaValues.x * Time.deltaTime * speedProgressiveLook,
            0f);
    }
}

void Update()
{
    // move
    _rigidbody.MovePosition(transform.position + (transform.forward * leftController.GetTouchPosition.y * Time.deltaTime * speedMovements) +
        (transform.right * leftController.GetTouchPosition.x * Time.deltaTime * speedMovements) );

    if(continuousRightController)
    {
        transform.localEulerAngles = new Vector3(transform.localEulerAngles.x - rightController.GetTouchPosition.y * Time.deltaTime * speedContinuousLook,
            transform.localEulerAngles.y + rightController.GetTouchPosition.x * Time.deltaTime * speedContinuousLook,
            0f);
    }
}

void OnDestroy()
{
    rightController.TouchEvent -= RightController_TouchEvent;
    rightController.TouchStateEvent -= RightController_TouchStateEvent;
}

}

Again, the question is how do I get a public variable Vector2 of the X and Y movement of the joystick, instead of directly moving the rigid body from inside this code.

Thanks for any help.

EDIT: The rigidbody is just in a primitive sphere for my testing purpose, it has nothing to do with the car prefab. I want to change the sphere for a car prefab and using the XY Vector I was talking about above alter the car controller code to take those values and accelerate, brake etc.


texts: Bullet: Get steepness or slope between positions

texts:
In a CharacterController object, there is

setMaxSlope(btScalar slopeRadians)
The max slope determines the maximum angle that the controller can walk up.

But how about knowing it in advance? Like check if the position where the character will move next is walkable (i don't know the correct word) or not? Is that possible? Any suggestions on how should I go about this?


texts:
I am looking into whether there is a way to balance the production and consumption of resources in a game over time, with the aim to allow both production and consumption to increase as various buildings and entities level up (or across various difficulty levels). For example a classic resource would be stone, wood, etc.
I am not looking for the initial values for building (those I suppose are set by testing it) but is there a formula or a logical process to calculate the increasing amount?

For example, at level 1 the "mine" produces 100 stone per hour and a “house” needs 120 stone to build. How should the production level increase for a mine at level 2-3-4-etc compared to the cost of building a level 2-3-4-etc house? Also, mine level 2 will cost more than level 1 obviously.

My problem is how to balance the game (starting with costs-productions).


texts: Isometric tiles math for 4:3 ratio (64 x 48 pixels)

texts:
I've read and tested the code from this article, http://clintbellanger.net/articles/isometric_math/, and also from this Isometric rendering and picking? and I can get the math and tile picking to work properly for a 2:1 isometric base tiles. However I haven't come across any article on tile picking math that involves a 4:3 ratio isometric base tiles. Can I just use the same math for the 4:3 ratio isometric or should I change it to make it work? If so, can anyone point me in the right direction of what is the right tile picking math for a 4:3 ratio isometric base tiles?

Thank you.


texts:
I'm working on a serious project and I really need help.

I'm working on a virtual reality First-Person-Shooter game. The problem is that I want to make the player (a real person) walk in place (about only 3 square meters) while playing, and give him the feel of walking, strafing and running, and at the same time detect the distance he should have moved in both axis if he wasn't playing (in real life).

I thought of making him wear shoes containing spheres at the bottom, or making them walk on sliding spheres, but all those are dumb ideas! Any good ideas?


texts: Where to start writing games, any tutorials or the like?

texts:
I'm actually an industrial systems developer with knowledge of .NET C# and VB.NET, C/C++, Delphi, and an intermediate knowledge of 80286 Intel assembly language.

I would be interested to learn how to develop games while taking as fully as possible advantage of my already acquired experience.

My first objective is to learn the differences between management and game software development so that I may make my mind up as to what is important to think about as a game developer.

Any hint as to where to start to learn is appreciated, such as game writing tutorials, the kind of "Hello World!" program, if I may say.

Besides, these following tutorials were found while "googling":

C++ Game Programming;
C and C++ Programming Games and Entertainment Tutorials;
C++ Game Programming Resource Center;
Creating a game in C++.

Are they any good?

The answer that will have guided me the most will be accepted. Thanks for your help! =)


texts: How to generate objects at specific intervals and make them move with same speed?

texts:
I'm creating an infinite runner where character has to jump on randomly generated pillars.
The pillars are positioned with a gap between each of them. The gaps are dmin and dmax.
In addition to this, i want the pillars to move to the left of screen with increasing velocity. But they all need to move with same velocity so that the gap in between them is maintained.
I have the script as follows:
pillar is a prefab.go is an empty gameobject which will later be used to Instantiate pillars.
first is the first pillar, manually positioned in the scene.

using UnityEngine;
    using System.Collections;

    public class GM : MonoBehaviour {
        float tempx,dmin=1.3f,dmax=3.5f;
        GameObject[] bins;
        Vector2 speed,pos,tempvel;
        public GameObject pillar,go;
        public Transform first;

        // Use this for initialization
        void Start () {
            speed = new Vector2 (-0.005f,0);
            tempx = first.transform.position.x;
            tempvel = new Vector2 (0, 0);
        }

        void Update () {
            if ((Vector3.Distance (go.transform.position,transform.position)<40f)) {

                tempx+=Random.Range(dmin,dmax);

                pos=new Vector2(tempx,-2.22f);

                go=Instantiate(pillar,pos,Quaternion.identity) as GameObject;
            }

            bins = GameObject.FindGameObjectsWithTag("trash");

            tempvel += new Vector2 (-0.0005f, 0);
            foreach (GameObject bin in bins) {

                //bin.GetComponent<Rigidbody2D>().velocity+=new Vector2(Random.Range(-0.005f,-0.05f),0);

                bin.GetComponent<Rigidbody2D>().velocity+=tempvel;
            }

        }
    }

Problem is, the speed of pillars increases way too fast. They move to the left at nearly invisible speeds. Also, after a certain speed, the gap between the pillars increases. They become so far apart, one is in camera view, another is somewhere far away.

Is there a way to accomplish this?


texts: Possible sizes of N in tiled Wave Function Collapse

texts: I've been attempting to implement tiled WFC, but I'm having trouble differentiating between the different flavors of the algorithm. When it comes to using tiles instead of pixels, most articles (including the github) use the Simple Tiled Model, in which N (size of patterns) is only 1x2. When using WFC in terms of pixels, N is usually 2x2, 3x3, or larger, which is what makes the algorithm so special. So, my question is: Will using an N greater than 1x2 yield desirable results when using tiled WFC?


texts: How to rotate a skybox cubemap using Unity Shadergraph

texts:
@Seyed Morteza Kamali solved his own problem of rotating a mesh cubemap with shadergraph here: How can I rotate cubemap in shadergraph?
However, I have a starry night cubemap inside my Skybox shader done in Unity Shader Graph, and as there is no way to directly attach a script to a Skybox material, I've been accessing the skybox material and the shader via external script. I've been using the Bolt visual scripting, and with this script, it is fairly easy to access other properties of the skybox but not the rotation (4x4 matrix). It is possible to access floats, vector2's, texture maps and even the Cubemap, but even if I have set the cubemap rotation, which to my knowledge has to be done with a Matrix 4, as an Exposed property, when trying to access it, e.g with FindPropertyIndex it gives the value -1, indicating that the property is not found.
Edit: ok, I found this in the Unity documentation:

Matrix parameters are not exposed in the material inspector, but can be set and queried with SetMatrix and GetMatrix from scripts.

As far as I understand the documentation, the example assumes a mesh renderer, which the skybox doesn't have. Another idea would be to use 3 vectors, which could be exposed and then apply the rotation somehow to them at the same time, I did some tests in this, but all I managed to create was to distort the cubemap.
Again I am not trying to rotate the entire skybox, but just a cubemap inside the skybox shader – this would allow different rotations to daytime clouds and nighttime stars.
Would be best if everything could be done inside ShaderGraph, with the speed and axis values published as properties. A custom function perhaps? I am using URP 7.2.0 and Unity 2019.3.0f6.


texts: 2D collision and getting closer to objects

texts:
Just curious what to do from here. So I am done with my tile editor program and currently have it set up so that my background (which is one large image) is mapped in XML to 32x32 tiles (again, a mapping, nothing is really split into tiles).

So when I have my character (this is a platformer rpg) comes across a tile which I have labeled as obstacle or something, they stop. This is nice and all except for some ugly space in between my character and tile where the edge of my rock is. I can't do pixel detection because it will never be sound.

For example, if my character's pinky ends up in the cell marked as an obstacle and for some reason, there is some black along an edge from a castle from the previous cell, this is a hit even though the player didn't actually touch any part of the rock but rather a part of the pinky hit that black edge.

The only thing I had which makes things seem to nicely lineup is to map it to a 16x16 array.

Edit: I will give the example with pic in the morning since site came back up but for now I'll give a better explanation.

My tile editor exports an XML file of my tile mapping...so, if I specified 32x32 tiles over an 800x600 image, my XML file will contain mappings for each 32x32 tile spread across the region. So I could have my XML file with tile 2 having a type of "Obstacle". I then in XNA just read the XML into a list storing each tile and their characteristics.

I then in my program do a collision check for now. In doing this, I create a rectangle around my player. Each time I move, I check for collision by doing this:

Does my rectangle intersect any collisions with a characteristic of obstacle or wall and so on...
If so, return true that a collision occurred.

So let's say that my background image has a blue background, a castle and a rock in the middle. In a tile I marked as being an obstacle, it contains a piece of the black wall of the castle and to the right of this is a piece of that rock along my path. So my character is now running to the right, will have an intersection with this obstacle tile and as a result, have something like 29 pixels between the player and the start of the rock. This collision occurred as the player hit a tile marked as an obstacle.

Using pixel color collision detection won't help either as a piece of my player could be hitting that black edge of the castle I talked about and the alpha values are never going to be 0.

I'll give a picture example but I am just detailing it a bit better for now.


texts: Any way to combine instantiated sprite renderers into one texture so I can apply into a plane at runtime?

texts:
So I am procedurally generating a tile set in Unity by instantiating different tiles that only have a transform and sprite renderer components. I managed to pack the sprites using unity sprite packer assigning them a packing tag so that I reduce the draw calls drastically.

But Im still having to deal with a great amount of game objects in the scene when the camera zooms out, increasing the batching and giving me problems when I try to apply light to them for example.

So I am trying to find a way to combine all these sprite renderers into a texture.So I can then apply this to a plane and Ill only have to deal with one plane gameObject for the map. But I cant figure out how to do this. I cant really use the combine meshes way as they are sprites only, not meshes. I tried taking a screenshot at run-time but It comes up a bit blurry. Any idea how can accomplish this?
Thank you for your help.


texts: Where to put common System functionality in Entity-System Design?

texts:
I am working on an Entity System design based largely off of Adam Martin's design and Ray Wenderlich's Objective-C Implementation.

I am working on the AI system using a state machine with a System for each state. However, many of these systems share a lot of functionality, for example:

-(NSArray*)findEnemiesOfEntity:(Entity*)entity withinRange:(float)range {
    // Get all entities with a Team component
    // Narrow down entities to those on opposing team
    // For those that have a Position component:
    //     Get their position
    //     If their position is within range:
    //         Add to array of return values
    // Return array of return values
}

Obviously this functionality could be used in many ways; for example, the AIDefendSystem could use it to know if it is safe to move to the Attack State and the AIAttackSystem could use it to know when to return to a Defensive State.

So my question is this: where does a function like the one above go in the design?

Things I have thought of so far:

A copy in each system: this seems quite redundant and hard to maintain.  Perhaps because other design approaches view this as a code smell, I can't quite bring myself to do it.
Inheritance hierarchy for systems: the common OOP solution to the problem of keeping a copy in each system.  This also seems like bad design as it will encounter the same sorts of inheritance problems ES was supposed to solve (e.g. what happens when a non-AI system needs to know how many enemies are within a given range).
A separate helper class with all these functions: to continue the database metaphor that Adam uses, I would interpret this as the "view" functionality in mysql. The downside to this would be a giant class full of seemingly unrelated helper functions
The above approach with a single class per functionality: solves the giant class problem but creates either a singleton nightmare or dependency injection nightmare.
Create another system with the functionality: this is the answer that "sounds" right, but I have no idea how it would work.

Let me know if I can provide any further detail or clarification. Thanks in advance!


texts: Is there a turn-based game service (like GKTurnBasedMatch on iOS) for desktops?

texts: Game Center's GKTurnBasedMatch seems to provide a pretty robust service for handling turn-based games, and OpenFeint appears to have something similar. The problem is, I'd like something like this for the desktop. I was thinking of rolling my own REST-based service on Rails, but after looking at the GameKit documentation, I realized it would take longer than I'd like to make it solid. I don't suppose something like this already exists that I missed in my searches?


texts: My cube goes through side walls on android device

texts:
I have a cube and it's on the ground and there are two walls (Plane) next to the ground.

Like in the image there is a ground and in side there is a wall.
Here is my code:

    void Update() {

      transform.Translate(userDirection * speed * 14f * Time.deltaTime);
    transform.Translate(mSpeed * Input.GetAxis("Horizontal") * 2 *  Time.deltaTime, 0f, mSpeed * Input.GetAxis("Vertical") * 2 *  Time.deltaTime);

    if (Input.touchCount == 0)
        return;
    Touch touch = Input.GetTouch(0);
    float originalY = transform.position.y;
    float cameraZ = Camera.main.WorldToScreenPoint(transform.position).z;

    if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Began) {
        Vector3 screenPoint = new Vector3(touch.position.x, touch.position.y, cameraZ);
        Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);
        worldPoint.y = originalY;
        transform.position = worldPoint;
    }
}

My cube goes through the side walls, but on laptop it works perfectly, and on android device my cube goes through the side walls. Can anyone please tell why is my cube is going through side walls?
Any help is appreciated!


texts:
I'm terribly sorry I'm asking this question YET AGAIN, but I can almost guarantee that this will be the last time I'll have to ask.

I'm currently on the verge of FINALLY getting these collisions to work for my game, made with libGDX in Java. My collisions use the same method as (and are basically copied and modified code from) the XNA Platformer example (here) where the direction of the collision is based on the rectangle where two objects are overlapping.

The collisions themselves almost work perfectly, but for some reason, holding down/up and left and colliding with the floor/ceiling while doing so doesn't seem to work well. I'm not at all sure why.

Instead of vaguely giving my problem and snippets of code, I've decided to instead provide a binary and the source of the game I have so far so you can see for yourself what my problem is. Link. (Note: make sure you unzip everything into a folder somewhere or it will not work)

You'll find the collision code in the method workingCollisions() in Link.java. Please excuse the messy code and terrible graphics as this whole thing is in pre-pre-alpha.

If anyone is kind enough and helps me out here, you are the best person ever. I'm completely desperate; I've been trying this on and off for months and I just can't get it to work. I cannot thank you enough.


texts: What is an appropriate OpenGL(ES)-based game engine meeting these criteria?

texts:
I want to try my hands on a little shooter on the Android platform, and I'm looking for a full-featured 3D game engine. I can't afford to pay more than 400 € for a license, so expensive engines are excluded from the start.

These are my requirements:

The engine has to have good level editor (able to place entities, actors and triggers); so "graphics engines" like Irrlicht and Horde 3D aren't what I'm looking for.
The engine should be based on OpenGL Core and use shaders rather than the fixed function pipeline.
It shouldn't use octrees and BSP/PVS.
It needs to have decent occlusion culling because I need good frame rates on not-very-powerful graphics cards.
It should come with source code.

I like Horde 3D very, very much and I like it's smart design, rendering capabilities and compactness. Sadly, I can't use it due to the lack of tools.

So far I've come across Torque 3D, C4 engine, Shiva 3D, and Unity 3D.

Torque 3D is really nice, decent design, has good tools, good performance, it's really cheap and comes with source code. Sadly it's only DirectX for now.
Unity has a lot of features, decent performance and tools, runs on Android but they don't give source code within my price range.
C4 is good enough, has tools, and source code but there's a catch. While you have source code the source isn't ported to Android and the engine's owner expressly forbids anyone to port source code on other platforms or to release a game on not officially supported platforms.
Shiva 3D seems nice, too, supports Android, has tools but they don't give you source code license for a decent sum.

That's all I could find. I used the list on devmaster.net, I searched this site, I've searched gamedev.net, gamasutra, polycount.com and of course Google and Bing.

Any suggestions that could help me?


texts: How can I implement bounding volume subdivision for my sprite images?

texts:
Lately, I have been researching different Collision methods, how to deal with multiple collisions and different types of bounding shapes, circles, rectangles, polygons and ellipsoids. Some common collision methods are the:

'Axis aligned bounding box'

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // collision detected!
}

'Circle Collision'

double dx = (circle1.x + circle1.radius) - (circle2.x + circle2.radius);
double dy = (circle1.y + circle1.radius) - (circle2.y + circle2.radius);
double distance = Math.sqrt(dx * dx + dy * dy);

if (distance < circle1.radius + circle2.radius) {
    // collision detected!
}

The bounding box/shape dilema

For one my projects, I am using images, which are rectangle by nature. However, to simply check for intersections with the images' edges would result in unsatisfactory collision detection. As Gamasutra puts it:

  " The experience of playing some of the early flight simulators
  illustrated how bad collision detection can ruin a game. Flying
  through a mountain peak and surviving isn’t very realistic. Even some
  recent games have exhibited collision problems. Many game players have
  been disappointed by the sight of their favorite heroes or heroines
  with parts of their bodies inside rigid walls. Even worse, many
  players have had the experience of being hit by a rocket or bullet
  that was “not even close” to them. "

From that resource I discovered an interesting method of making bounding boxes or circles which Gamasutra calls subdivision

I am having trouble thinking how to do this subdivision process for my images (as I am working with images) and how to properly implement either subdividing process within my collision reliant app.

For example take mario and a koopa shell. I wouldn't want their transparent space to trigger intersection


texts: Unsure how to decide ray intersection interval

texts: I'm coding an intersection algorithm with AABB, as found here. However, I'm absolutely unsure what to pass in as t0 and t1. The paper states that it's a ray intersection interval, but the only material I've been able to find on this is that it's some kind of guess or bound as to the final values. Any suggestions as to how to define t0 and t1?


texts: Rotating a Sprite and Moving It along That Angle in Unity

texts:
first time posting here. What I want to do seems extremely simple, but I'm not familiar enough with Unity to be able to implement it. Also, I wasn't able to find an answer that exactly solved my problem, but I'm sure it's simple enough.

I'm trying to rotate a sprite based on left arrow down and right arrow down:

    if (Input.GetKey (KeyCode.RightArrow)) {
        this.transform.Rotate (new Vector3(0, 0, -2));
    }

    if (Input.GetKey (KeyCode.LeftArrow)) {
        this.transform.Rotate (new Vector3(0, 0, 2));
    }

Once the sprite has been rotated, I would like to be able to apply a force in the direction it's facing by holding down the up arrow. And when the down arrow is held down, apply a negative force (or the same force in the opposite direction).

Here's what I have thus far:

    if (Input.GetKeyDown (KeyCode.UpArrow)) {
        Vector2 direction = new Vector2 (Mathf.Cos(body.rotation), Mathf.Sin(body.rotation));
        body.AddForce (direction * 10);
    }

This code just moves it along some unchanging angle that body (Ridigbody2D) has. Again, this is probably an extremely simple issue, but I can't seem to find anything that helps. I know I'll probably feel like an idiot when I see the solution!


texts:
Here is my working piece of code to rotate an image toward a point (in my case, the mouse cursor).

float dx = newx - ploc.x;
float dy = newy - ploc.y;
float angle = (float) Math.toDegrees(Math.atan2(dy, dx));

Where ploc is the location of the image i'm rotating.

And here is the rendering code:

g.rotate(loc.x + width / 2, loc.y + height / 2, angle);
g.drawImage(frame, loc.x, loc.y);

Where loc is the location of the image and "width" and "height" are respectively the width and height of the image.

What changes are needed to make it works on a scaled context? e.g make it works with something like g.scale(sx, sy).


texts: I'm toying around with the new Sprite class in Unity, and I'm trying to work out how to change the direction the sprite is facing ("flip" it). I'm sure I can most likely just scale it across the x axis by -1, but I'd just like to know if there's a new, "official" way of doing it with Sprite or SpriteRenderer. Thanks!


texts: Was Chrome AngryBirds game made using html5 canvas? And if yes: what kind of engine did they use?


texts: Position of an object relative to another in a 2D plane

texts:
I have two objects, A and B, each of them has a set of coordinates (x,y). How do I understand where is A in relation to B's position?

If I where to just check each coordinates I could do it like this:

B(x:5,y:5), A(x:4,y:5);
x = 5-4 = 1;
y = 5-5 = 0;
A it's on the left

B(x:5,y:5), A(x:6,y:5);
x = 5-6 = -1;
y = 5-5 = 0;
A it's on the right

B(x:5,y:5), A(x:5,y:6);
x = 5-5 = 0;
y = 5-6 = -1;
A it's on top of B

B(x:5,y:5), A(x:6,y:5);
x = 5-5 = 0;
y = 5-4 = 1;
A it's under B

But I was wondering, since I'm using a standard Vector2 data structure (from LibGDX), with the ability to normalize, compute distances, etc.. If I could do it using those methods instead of subtracting the coordinates each time.

If it can help, I need to know the position of A relative to B because A is supposed to push B, so if A it's on B's left, B needs to move right, etc...


texts: In GameMaker how to check if instance is a given object?

texts:
Let's say, I have three objects: obj_square, obj_circle and obj_triangle.

Instances of all three types of objects exists in the room and call the same script: scr_test.

Inside of this script, how can I check instance of which object is calling it?

Pseudocode:

if(self is instanceof(obj_circle))
{
// do stuff
}


texts:
I was searching for a game engine (Java- maybe C#) with built-in real time networking library to develop 2D cross platform (Android - iOS) multiplayer game. Actually I have not found well suited solution apart from Unity, however I don't like some of the features of Unity. (Here is Discussion)

After a while I decided to use Libgdx and tried to find a network libray that meets my requirements and I found Raknet as network engine which is written in C++ and cross-platform. So here is my question:

Is there any way to use Raknet with Libgdx, or any other solutions you recommend as engine or anything else? And also is it possible to use any C/++ library with Libgdx like Android's NDK?


texts: SDL 2 SDL_BLENDMODE_BLEND way faster. Why?

texts:
I was just tinkering around with a simple ecs, when I noticed drawing like 20,000 rectangles killed my
framerate (~10 FPS). I thought ok, maybe it's just too many.
Later I wanted to draw them transparent and set the blend mode to SDL_BLENDMODE_BLEND. Now I can draw
around 60,000 of them with 60 FPS.
I figured maybe it's because of pixel format conversion or something alike. When I use getWindowPixelFormat I get RGB888. No I'm even more confused because of the lacking alpha channel.
Code (abbreviated):
SDL_Window *window  = SDL_CreateWindow("Test",
                                       SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                       1280, 720,
                                       wndFlags);

SDL_Renderer *renderer  = SDL_CreateRenderer( window, -1,
                                             SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
while(running) {
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0xFF, 0xFF);
SDL_RenderFillRect(renderer, &rect);
SDL_RenderPresent(renderer)
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);
}

Could someone enlighten me please?


texts: removing triangle artifacts from overlapping height maps OpenGL

texts:
I have two 100x100 height maps that I am drawing using a triangle mesh. One represents the land height, and the other represents (water + land) height.

I currently draw both meshes on top of each other, and I make the water mesh transparent when the water level is 0.

But where the land meets the water there are lots of artifacts.

I believe the cause is the water mesh is >= the height of the land mesh so at the edges the water mesh height goes from being > land mesh height to == , the visible slope is actually the water mesh slope and not the land mesh slope.

That said, I don't know any good way to fix it.

Note: water level may not be flat so replacing the water mesh with a plane wont work


texts: Pygame collision detection less frequent when objects are increased

texts:
I currently experiencing an issue in pygame where whenever i increase the number of objects e.g. platforms, rocks

for a in range(150):
    rock = Rock(0,0)

OR incresing the range which they spawn in:

rock.rect.x = random.randrange(-200,30000)
rock.rect.y = random.randrange(80,500)
rock_list.add(rock)
all_sprites_list.add(rock)

LINE 232

(which i really need to do for an ENDLESS mode) collision detection between the player and all the objects that have have been changed will become less frequent, so the character will just go through th objects as they weren't even there... you can see the character fall through the objects, it falls through in front of the object and not behind. All game code is below, I have tried a number of different techniques and values but I have found that these numbers and ranges work best.

Collision Detection code:
 FOR PLATFORM

medium_collide = pygame.sprite.spritecollide(player, medium_list, False)
if medium_collide:
    player.rect.y-=2

FOR ROCK

    rock_collide = pygame.sprite.spritecollide(player, rock_list, True)
    if rock_collide:
        lives-=1
    if rock_collide:
        player.rect.y = 100
        player.rect.x = 50

!!!!!GAME CODE BELOW!!!!!

GAME CODE


texts: Is it possible to extract textures or sprites from compiled game files?

texts: For instance, every map in Portal has what appear to be sprites over a texture indicating the obstacles you'll face (see screenshot). Are these resources compiled into the source as byte code, or is it possible to extract them from installation files? Obviously I understand copyright implications, and I am only interested in using it for a recreational project. Instead of recreating them, I wonder if they can be extracted.


texts:
I'm trying to produce a shader to replicate a white plastic object with a colored light inside. Either by having a shader that will be translucent and if I put a light inside the object the light will show through or by having a shader that fakes the effect of a light inside.

The effect im going for is kinda like a light going through a lamp shade similar to these pictures:

Ideally I would be able to control the strength and colour of the light to get it to pulse and rotate through some nice bright fluro colours

Though I'm not sure where to start!

My question is does anyone know the techniques I should be researching to be able to produce such a shader or have an example of the same/similar shader I can use as a starting point? Or even if you want to provide a shader that might do the job


texts: Why do the ALPHA channel in TGA is not visible?

texts:
Good morning GDSE,

I am loading a TGA using loadTGA function found in superbible 4th edition source code.
Here is how the image looks in Gimp

You can see I have enabled alpha channel in Gimp, I exported this to TGA image, without RLE compression, and 32bpp. But when I load the image in my OpenGL code, the part of the image which is supposed to be transparent is seen white.

Where I must be going wrong? The type of TGA is set to GL_RGBA, 32 bpp.

Here is my Fragment shader code.

out_fragColor = (vec4( ambAndDiff, 1 ) * texColor) + vec4(spec,0.0);

I have calculated ambAndDiff and spec values earlier using ADS phong shading, and both of them are vec3.
Let me know if you also want to view the TGA loading code. :)

Regards,
A.


texts: Weapon RPS - circular list; troubles keeping circular list balanced when expanding

texts:
I've got a idea for a game in the works, and I'm trying to figure out how to sort 17 weapons into a circular list where each weapon beats the 8 below it but loses to the 8 above it. Currently, I only have an RPS-5 figured out where each beats the 2 below it but loses to the 2 above it:

bow
daggers
magical orb
gun
glaive

I then set out to try to expand it into an RPS-7, starting by adding one weapon and creating a placeholder spot to find the most appropriate weapon for. I came up with "spear", which I determined beats "magical orb" and "glaive" but loses to "bow", "daggers", and "gun". What with "gun" being smack between the two things that "spear" beats though, where do I put the placeholder spot? I'm assuming if it's even possible without giving up on my well thought reasons for why what beats what I'll need more than 1 placeholder spot to find an appropriate weapon for.

Is it at all possible to place the placeholder spots such that "spear" ends up above "magical orb" and "glaive" while still being below "bow", "daggers", and "gun"? Or will I have to either alter an interaction or see if I can create a perfectly imbalanced RPS?

If this question would benefit from additional tags, please let me know.


texts: Vector3 vs. Vector2 - performance, usage?

texts:
I'm currently playing around with XNA, and creating a simple 2D platformer. I was thinking of adding multiple layers to make it a little bit of challenge.

In stead of having a Vector2 for my positions, I now use a Vector3, solely to use it's Z as layer depth. However, since you can't use operators between Vector2 and Vector3 for some unknown reason [1], I ended up changing all other Vector2s in my game, such as acceleration, speed and offset, so I can do things like position +=  offset without errors.

I also changed my rotation variable from float to Vector3, and I use the Z value to rotate my textures. I'm planning to use the X and Y to scale-flip my textures, so you get the Super Paper Mario effect.

However, after changing all these Vector2s in Vector3s, I felt a little bad about it. How does this effect the performance of games? I know I shouldn't have to worry about performance in my little platformer game, but I'm just curious about it.

Is there any notable performance between Vector2s and Vector3s, for example when adding or multiplying them, or when calling Normalize, Transform, or Distance?

[1] Just a side question, why are there no operators for calculations between Vector3 and Vector2?


texts:
I am working on a game which consists of 3D elements and a 2D GUI. I have it working properly, but I want to enable multisampling for only the 3D parts, and not the 2D Textures. Otherwise, the GUI icons become blurred.

Here is the code for my Draw method

    protected override void Draw(GameTime gameTime)
    {
        graphics.PreferMultiSampling = true;
        graphics.ApplyChanges();

        GraphicsDevice.Clear(Color.Black);

        GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;

        foreach (Element e in Elements)// 3D part
        {
            e.Draw(GraphicsDevice, camera);
        }

        graphics.PreferMultiSampling = false;
        graphics.ApplyChanges();

        spriteBatch.Begin();
        UIM.Draw(GraphicsDevice, spriteBatch);
        spriteBatch.End();//

        base.Draw(gameTime);
    }

Using this code, I get an exception because all of my Texture2Ds dispose for some reason.

Is there a way to change the MultiSampling in the middle of the Draw method?


texts: how to script a match 3 game without waiting for matches to finish

texts:
I have developed a full match 3 game without the ability of making another move until all cascading is finished.

I was stuck trying to figure out how to do it with the ability of making moves even if the previous moves have not finished yet. I can't figure out the programing logic behind it, I tried different approaches with no luck so far, the results came up messy.

Can any one help.

Thanks in advance.


texts: Points inside a Polygon, failing for shapes with 0,0

texts:
I've been using an algorithm (http://wiki.unity3d.com/index.php/PolyContainsPoint) to tell me if a point is inside a polygon... in fact a few variants (here and here) but they all come back the same. Shapes with (0,0) vertices fail.

Here's the function:

private bool IsPointInPolygon(Vector2[] polyPoints, Vector2 p)
{
    int j = polyPoints.Length-1;
    bool inside = false;
    for (int i = 0; i < polyPoints.Length; j = i++) {
        if ( ((polyPoints[i].y <= p.y && p.y < polyPoints[j].y) || (polyPoints[j].y <= p.y && p.y < polyPoints[i].y)) &&
            (p.x < (polyPoints[j].x - polyPoints[i].x) * (p.y - polyPoints[i].y) / (polyPoints[j].y - polyPoints[i].y) + polyPoints[i].x))
            inside = !inside;
    }
    return inside;
}

And here's the testing output for a number of 'cloned' squares being translated around the original square (original shown in black in the diagram) - Notice all the squares with the 0,0 fail. Why is this? I don't really know what the algorithm is doing but have tried a few with exactly the same result..

Vector origin (0.0, 0.0) to Vector destination (1.0, 0.0)
distance: (1.0, 0.0)
New Shape 1 0
New Shape 2 0
New Shape 2 1
New Shape 1 1
PASS

Vector origin (0.0, 0.0) to Vector destination (1.0, 1.0)
distance: (1.0, 1.0)
New Shape 1 1
New Shape 2 1
New Shape 2 2
New Shape 1 2
PASS

Vector origin (0.0, 0.0) to Vector destination (0.0, 1.0)
distance: (0.0, 1.0)
New Shape 0 1
New Shape 1 1
New Shape 1 2
New Shape 0 2
PASS

Vector origin (1.0, 0.0) to Vector destination (0.0, 0.0)
distance: (-1.0, 0.0)
New Shape -1 0
New Shape 0 0
New Shape 0 1
New Shape -1 1
FAIL

Vector origin (1.0, 0.0) to Vector destination (1.0, 1.0)
distance: (0.0, 1.0)
New Shape 0 1
New Shape 1 1
New Shape 1 2
New Shape 0 2
PASS

Vector origin (1.0, 0.0) to Vector destination (0.0, 1.0)
distance: (-1.0, 1.0)
New Shape -1 1
New Shape 0 1
New Shape 0 2
New Shape -1 2
PASS

Vector origin (1.0, 1.0) to Vector destination (0.0, 0.0)
distance: (-1.0, -1.0)
New Shape -1 -1
New Shape 0 -1
New Shape 0 0
New Shape -1 0
FAIL

Vector origin (1.0, 1.0) to Vector destination (1.0, 0.0)
distance: (0.0, -1.0)
New Shape 0 -1
New Shape 1 -1
New Shape 1 0
New Shape 0 0
FAIL

Vector origin (1.0, 1.0) to Vector destination (0.0, 1.0)
distance: (-1.0, 0.0)
New Shape -1 0
New Shape 0 0
New Shape 0 1
New Shape -1 1
FAIL

Vector origin (0.0, 1.0) to Vector destination (0.0, 0.0)
distance: (0.0, -1.0)
New Shape 0 -1
New Shape 1 -1
New Shape 1 0
New Shape 0 0
FAIL

Vector origin (0.0, 1.0) to Vector destination (1.0, 0.0)
distance: (1.0, -1.0)
New Shape 1 -1
New Shape 2 -1
New Shape 2 0
New Shape 1 0
PASS

Vector origin (0.0, 1.0) to Vector destination (1.0, 1.0)
distance: (1.0, 0.0)
New Shape 1 0
New Shape 2 0
New Shape 2 1
New Shape 1 1
PASS


texts: I need an analytic formula for 3 arms inverse kinematics system

texts:
I need an Analytic formula for 3 arms IK system_. I'm currently using Fabrik and CCD solutions but I'm facing low-performance and accuracy issues. So now I'm looking for an Analytic formula.

I'm working on a planar system so a 2D solution would work.

Thanks in advance for any help.


texts: How to restrict jumping to a single jump?

texts:
I'm making a VolleyBall game in HTML5 with PandaJs GameEngine and plugin is used physics and Box2D.

The problem is that players can jump, but they can jump over the net with multiple jumps. I have already implemented collision detection but i don't know how the restrict move space for player. I also attaching my screen shot here so look at this
:

In the picture Player1 goes Player2 side and vise-versa.


texts: Geometry Shader not generating geometry for some Vertices

texts:
I am playing with a geometry shader and I am wondering why it doesn't generate geometry for each vertex in all meshes?

I don't think this is a Cull problem because the same vertices generate geometry as you rotate around and setting Cull Off changes nothing.
Another problem could be a multiply by zero somewhere but I tried to eliminate as many variables as possible and still have the issue.
A third unlikely issue could be limiting the output amount somewhere. I didn't set anything explicitly to hinder that.

I notice the problem on a Cube(5/8) and Quad(2/4) but seems to generate all the geometry fine on a plane, cylinder, etc. The following are some results from using the bare-bones geometry shader.

Cube (closest: Unity default, further back: Cinema 4D exported .fbx cube):

Quad:

It seems to work fine on a plane (update: It is actually missing a whole row on each axis)

Unity Shader Code GeometryShaderTest1.shader:

Note: If you are testing out the shader and nothing is displaying; Rotate your camera around so the normals are facing the right direction to show up.

Shader "Custom/GeometryShaderTest1" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _Amount ("Height Adjustment", Float) = 0.0
    }
    SubShader {
        Pass {
            Tags { "RenderType"="Opaque" }
            LOD 200

            CGPROGRAM
            #pragma target 5.0
            //#pragma addshadow
            #pragma vertex vert
            #pragma geometry GS_Main
            #pragma fragment frag
            #include "UnityCG.cginc"

            // Vert to geo
            struct v2g
            {
                float4 pos: POSITION;
            };

            // geo to frag
            struct g2f
            {
                float4 pos: POSITION;
            };

            // Vars
            fixed4 _Color;
            float _Amount;

            // Vertex modifier function
            v2g vert(appdata_base v) {

                v2g output = (v2g)0;
                output.pos = mul(_Object2World, v.vertex);
                // Just testing whether all vertices affected
                output.pos.y -= _Amount;

                return output;
            }

            // GS_Main(point v2g p[1], inout TriangleStream<g2f> triStream)
            // GS_Main(line v2g p[2], inout TriangleStream<g2f> triStream)
            // GS_Main(triangle v2g p[3], inout TriangleStream<g2f> triStream)
            [maxvertexcount(4)]
            void GS_Main(point v2g p[1], inout TriangleStream<g2f> triStream)
            {
                float4 v[4];

                float3 asdfUp = float3(0, 1, 0);
                float3 asdfRight = float3(0, 0, 1);
                v[0] = float4(p[0].pos + 0.25 * asdfRight - 0.25 * asdfUp, 1.0f);
                v[1] = float4(p[0].pos + 0.25 * asdfRight + 0.25 * asdfUp, 1.0f);
                v[2] = float4(p[0].pos - 0.25 * asdfRight - 0.25 * asdfUp, 1.0f);
                v[3] = float4(p[0].pos - 0.25 * asdfRight + 0.25 * asdfUp, 1.0f);

                float4x4 vp = mul(UNITY_MATRIX_MVP, _World2Object);
                g2f pIn;
                pIn.pos = mul(vp, v[0]);
                triStream.Append(pIn);

                pIn.pos = mul(vp, v[1]);
                triStream.Append(pIn);

                pIn.pos = mul(vp, v[2]);
                triStream.Append(pIn);

                pIn.pos = mul(vp, v[3]);
                triStream.Append(pIn);
            }

            fixed4 frag(g2f input) : COLOR {
                return float4(1.0, 0.0, 0.0, 1.0);
            }

            ENDCG
        }

    }

    FallBack "Diffuse"
}

Geometry shader resources:

Geometry shader with shadows not displaying shadows properly - Unity forums
This isn't exactly OpenGL but good info: Geometry Shader and Vertex Shader
Billboarding Geometry shader example here and here


texts: Marshalling C# Structs into DX11 cbuffers

texts:
I'm having some issues with the packing of my structure in C# and passing them through to cbuffers I have registered in HLSL. When I pack my struct in one manner the information seems to be able to pass to the shader:

[StructLayout(LayoutKind.Explicit, Size = 16)]
internal struct TestStruct
{
    [FieldOffset(0)]
    public Vector3 mEyePosition;

    [FieldOffset(12)]
    public int type;
}

This works perfectly when used against this HLSL fragment:

cbuffer PerFrame : register(b0)
{
    Vector3 eyePos;
    int type;
}

float3 GetColour()
{
    float3 returnColour = float(0.0f, 0.0f, 0.0f);

    switch(type)
    {
        case 0:
            returnColour = float3(1.0f, 0.0f, 0.0f);
            break;
        case 1:
            returnColour = float3(0.0f, 1.0f, 0.0f);
            break;
        case 2:
            returnColour = float3(0.0f, 0.0f, 1.0f);
            break;
    }

    return returnColour;
}

However, when I use the following structure definitions...

// Note this is 16 because HLSL packs in 4 float 'chunks'.
// It is also simplified, but still demonstrates the problem.
[StructLayout(Layout.Explicit, Size = 16)]
internal struct InternalTestStruct
{
    [FieldOffset(0)]
    public int type;
}

[StructLayout(LayoutKind.Explicit, Size = 32)]
internal struct TestStruct
{
    [FieldOffset(0)]
    public Vector3 mEyePosition;

    //Missing 4 bytes here for correct packing.

    [FieldOffset(16)]
    public InternalTestStruct mInternal;
}

... the following HLSL fragment no longer works.

struct InternalType
{
    int type;
}

cbuffer PerFrame : register(b0)
{
    Vector3 eyePos;
    InternalType internalStruct;
}

float3 GetColour()
{
    float3 returnColour = float(0.0f, 0.0f, 0.0f);

    switch(internaltype.type)
    {
        case 0:
            returnColour = float3(1.0f, 0.0f, 0.0f);
            break;
        case 1:
            returnColour = float3(0.0f, 1.0f, 0.0f);
            break;
        case 2:
            returnColour = float3(0.0f, 0.0f, 1.0f);
            break;
    }

    return returnColour;
}

Is there a problem with the way I am packing the struct, or is it another issue?

To re-iterate: I can pass a struct in a cbuffer so long as it does not contain a nested struct.


texts:
I have a world that I want to divide in two like this:

 ____________________
|                    |
|                    |
|        A           |
|                    |
|                    |
|____________________|
|                    |
|                    |
|        B           |
|                    |
|                    |
|____________________|

And I want the gravity in A to go up and in B to go down.

How can I implement a world like this using Box2D?


texts: Third-person Steering with Samsung Gear VR Unity

texts:
I am working on third-person steering, where you see the object like car, plane, spaceship in front of you as you steer it. I have got the code for Google Cardboard . How can I implement this in Samsung Gear VR with Unity?

public float speed = /* some number */;

private CardboardHead head;

void Start()
{

 head = Camera.main.GetComponent<StereoController>().Head;

}

 void Update()

 {
     transform.position += speed * head.Gaze.direction;
  }


texts: What is the shader format for Metal shaders shipped with iOS applications?

texts:
I am interested in analyzing existing shaders implemented using Apple's Metal framework. From my previous experience on other platforms with OpenGL, I have found that applications sometimes bundle shader code more or less in plaintext within the application binary. I have not found this to be the case with iOS.

Is there a special final format that Metal shaders are compiled into?
Can they be disassembled?
Where should one normally look for shader code in iOS applications?

Please let me know if this isn't posted on the right SE before downvoting. I was torn on whether this should go on Graphics SE or GamesDev SE. I do not think this should go on ReverseEngineering, or Security SE, as I fear those communities have very little experience with shader formats and likely wont be much help.


texts: What actions should I perform in DirectX 11 to correctly process Alt+Tab?

texts:
What actions, should I perform in a DirectX 11 application to correctly process Alt+Tab events from Windows?
My application is in fullscreen mode.
I expect my application to minimize to taskbar nicely, but it freezes for 20 seconds instead and no window minimization happens.
I know I can minimize the window by calling to ShowWindow, but what's up with the freeze?


texts:
I've coded up a little grid based dungeon game. Everything working quite nicely in a Tile[,]. The AI uses basic GOAP for tasks and A* for moving around. Tile reachability is done using a floodfill.

Thinking about what my next step would be, I decided to change the art style from being the typical dungeon to a more sci-fi approach and thought it'd be great to have multiple levels.

This is where I ran into a problem because A* in a 2d grid I understand. But adding extra levels makes it a wee bit harder. My initial thoughts would be to add connections to the next levels in 'stairs' or 'elevator' tiles and adding these to the neighbor list of a Tile for evaluation by A*.

But this throws my heuristic for a loop. I'm using Manhattan distance.

TL;DR: How should I improve my heuristic for multi level path finding?


texts: How do I set the Jump distance and height of my sprite in C#

texts:
I have been able to make my sprite jump for a platformer I am making in unity. I can't seem to be able to make him jump a certain height or distance though, every time he jumps it's like he's jumping on the moon, any suggestions? Here's my code:

using UnityEngine;
using System.Collections;

public class playerScript : MonoBehaviour {
    public bool grounded = true;
    public float jumpPower = 190;
    public float jumpSpeed = 100f;

private bool hasJumped = false;

// Use this for initialization
void Start () {
}

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

    if(!grounded && GetComponent<Rigidbody2D>().velocity.y == 0) {
        grounded = true;
    }
    if (Input.GetKey(KeyCode.Space) && grounded == true) {
        hasJumped = true;
    }   GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumpSpeed);
}

void FixedUpdate (){
    if(hasJumped){
        GetComponent<Rigidbody2D>().AddForce(transform.up*jumpPower);
        grounded = false;
        hasJumped = false;
    }
}

Any help would be greatly appreciated :)


texts:
I'm starting to implement a real-time PBR shading pipeline in one of my projects and had a few questions that I thought folks around here could help clarify.

1) Is it fair to say that in a PBR shading model, you'd typically have two separate BRDFs - one for specular and one for diffuse? So far, I've been using a simple Lambertian diffuse term and a more complicated BRDF for specular (i.e. one that uses a normal distribution function, a geometric shadowing term, and fresnel attenuation). At the end of my shading routine, I simply add these two terms together.

2) Why do so many diffuse models ignore surface roughness? I don't understand why the microfacet model wouldn't drastically change the way light is refracted, scattered, and re-emitted through a surface (i.e. the diffuse term).

3) People often parameterize this material model with three variables: roughness, metallic, and specular. In my current model, I use 'roughness' for various calculations in the specular BRDF. Obviously, the Lambertian diffuse model doesn't take into account the surface roughness, but I may adopt a more advanced shading model later (i.e. Oren-Nayar). I use 'metallic' to blend between the diffuse and specular terms. It also controls the color of the specular highlight - a higher 'metallic' value will result in highlights that are tinted towards the diffuse color of the material, while lower values result in highlights that are white. Finally, 'specular' just controls the final intensity of the specular highlight. Does this make sense?

4) I'm confused where environment maps, irradiance maps, and pre-filtered cube maps fit into this model. Is it fair to say that irradiance maps are used for indirect diffuse lighting, pre-filtered cube maps are used for indirect specular lighting, and environment maps are used for reflections (based on how 'metallic' a material is)? The relationship between direct and indirect lighting in a PBR material model is confusing to me.

Any help would be greatly appreciated. Thanks all


texts:
I am developing a simple cocos2d game in which I want to animate two CCSprites simultaneously, and for this purpose I simply set CCActions on respective `CCSprite's as follows.

[first runAction:[CCMoveTo actionWithDuration:1 position:secondPosition]];
[second runAction:[CCMoveTo actionWithDuration:1 position:firstPosition]];

Now I want to wait till the animations are complete, so I can perform the next step. How should I wait for these animations to finish?

There are actually two method calls, the first one animates the objects via the code above and second call does the other animation.

I need to delay the second method call until the animations in first are complete. (I would not like to use CCCallFunc blocks as I want to call the second method from the same caller as the first one.


texts: How to transfrom CollisionPolygon2D according to the Vertex Shader applied to a Sprite?

texts:
Consider this:
* KinematicBody2D
- * Sprite
- * CollisionPolygon2D

And a vertex shader:
shader_type canvas_item;

void vertex() {
    VERTEX.y += sin(2.0 * TIME) * 10.0;
}

When the vertex shader is added to the CanvasItem.material of the Sprite and the CollisionPolygon2D they both move at the same time:

But if one modifies the shader like that:
void vertex() {
  VERTEX.y += sin(UV.y * 2.0 * TIME) * 10.0;
}

It produces that:

How to transfrom CollisionPolygon2D according to the Vertex Shader applied to the Sprite?


texts: XNA - how to prevent a sound from looping

texts:
So in XNA I have this code:
Variables:

SoundEffect optionSelected;

In the LoadContent() method:

optionSelected = Content.Load<SoundEffect>("gameSounds\\selectOption");

In the Update() method:

optionSelected.Play();

So when it comes time for the sound to play it never stops looping. I want to hear it only once. How to achieve that? Thanks in advance!


texts: Sprite rotation: is it better to rotate with a quaternion or via sprite swap?

texts:
Considering this question:
"In a generic game engine where you have an object sprite (e.g. Unity), is it better (in terms of performance) to implement a clockwise rotation calculating at each frame the incremented rotation (e.g. having a quaternion "q" representing a rotation of n degrees and at each frame computing newrotation = q * oldrotation) or having say 20 snapshot sprites of a complete rotation and changing the sprite at each frame (effectively a 2D animation)? "

Is there a non engine-specific answer to this question? If so, which one?


texts:
I am developing a game in 2D using LWJGL library.

So far I have a rotating box. I have done basic Rectangle collision, but it doesn't work for rotated rectangles.

Does OpenGL have a function that returns the vertices of rotated rectangle? Or is there another way of doing this using trigonometry?

I had researched how to do this and everything I found was using some matrix that I don't understand so I am asking if there is another way of doing this.

For clarification, I am trying to find out the true (rotated) X,Y of each point of the rectangle. Let's say, the first point of a rectangle (top,left) has x=10 y=10.. Width and height is 100 pixels. When I rotate the rectangle using glRotatef() the x and y stay the same. The rotation is happening inside OpenGL. I need to extract the x,y of the rectangle so I can detect collisions properly.


texts:
i'm creating a game with flixel, and I want to have a effect when you mouse over a tile, I tried implementing it, and this is what it gives:

    public class GameState extends FlxState
{
    private var block:EmptyBlock;
    public function GameState()
    {

    }

    override public function create():void {
        for (var i:Number = 0; i < 30; i++) {
            block = new EmptyBlock(i, 20);
            block.create();
        }
    }

    override public function update():void {
            block.update();
            super.update();
    }
}

}

GameState class

and here is the EmptyBlock class:

public class EmptyBlock
    {

    private var x:int;
    private var y:int;
    private var row:FlxRect
    public function EmptyBlock(x:int, y:int )
    {
        this.x = x;
        this.y = y;
    }

    public function create():void {
         row = new FlxRect(x, y, 32, 32);
        trace ("Created block at" + x + y);
    }

    public function update():void {
        if (FlxG.mouse.screenX == row.x) {
            if (FlxG.mouse.screenY == row.y) {
                var outline:FlxSprite = new FlxSprite(row.x, row.y).makeGraphic(row.width, row.height, 0x002525);
            }
        }
    }

}

}

UPDATE:

The problem is still not solved.

I tried what you recommended, this is the new code:

  public class EmptyBlock extends FlxSprite {
       private var outline:FlxSprite;
       [Embed(source = 'freetile.png', mimeType="image/png")] private var    freeTile:Class;
    public function EmptyBlock(x:int, y:int) {
        this.x = x * 32;
        this.y = y;
        width = 32;
        height = 32;

        // Note: this is a block, rather than an outline.
        // Create an outline image, then use loadGraphic()
        // instead of makeGraphic() if you want an outline.
        outline = new FlxSprite(this.x, this.y);
        outline.loadGraphic(freeTile, false, false, 32, 32, false);
    }

    override public function draw():void {
        super.draw();
        if (overlapsPoint(FlxG.mouse.getScreenPosition()))
            outline.draw();
    }
}
}

And I call it here:

        public function  createMap():void {
        var block:EmptyBlock = new EmptyBlock(0, 0);
        block.draw();

    }

Do you see what i'm doing wrong?

Thanks!


texts: What's the best way to move cars along roads

texts:
I am implementing car movement game (sort-of like Locomotion). So 60 times a second I have to advance the movement of each car. The problem is I have to look ahead to see if there is a slower car, stop sign, or red light ahead. And then slow down appropiately.

I also want to have the cars take time to go from stopped to full speed and again to slow down. I'm not implementing full-blown physics, but just a tick by tick speed up/slow down as that provides most of the realism to match what people expect to see.

The best I've come up with is to walk out the full distance the car would travel of it was slowing to a stop and see if anywhere along that path it needed to slow down or stop. And then move it forward appropiately.

I am moving the cars 60 times a second so I need this to be fast. And walking out that whole path each tick strikes me as processor intensive.

What's the best way to do this?


texts:
I am working on a Pacman clone. I am using Java for the project. I have been having problems with collisions, and allowing the player to pass through objects. Note that the tile size (and player) is 16x16px.

Here is the collision code in the player class.

private void processInput(Input input, int delta)  {
    if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_RIGHT) ||
        input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_DOWN))  {

        if (input.isKeyDown(Input.KEY_LEFT))  {
            velocity =  new Vector2(-1 * speed * delta, 0);

            rotation = 180f;
        }
        else if (input.isKeyDown(Input.KEY_RIGHT))  {
            velocity = new Vector2(1 * speed * delta, 0);

            rotation = 0f;
        }
        else if (input.isKeyDown(Input.KEY_UP))  {
            velocity = new Vector2(0, -1 * speed * delta);

            rotation = 270f;
        }
        else if (input.isKeyDown(Input.KEY_DOWN))  {
            velocity = new Vector2(0, 1 * speed * delta);

            rotation = 90f;
        }
    }

    processCollision();

    this.position.x += velocity.x;
    this.position.y += velocity.y;
}

private void processCollision()  {
    this.positionTile = new Vector2(position.x, position.y);

    this.positionTile.x -= board.getX();
    this.positionTile.y -= board.getY();

    this.positionTile.x /= 16;
    this.positionTile.y /= 16;

    Vector2 normalisedVelocity = new Vector2(velocity.x, velocity.y);
    normalisedVelocity = velocity.getNormal();

    if (collision(normalisedVelocity))  {
        velocity = Vector2.ZERO;
    }
}

private boolean collision(Vector2 direction)  {
    Vector2 index = new Vector2(positionTile.x + direction.x, positionTile.y + direction.y);

    if (!board.getTiles()[(int)index.y][(int)index.x].collidable)  {
        return true;
    }

    return false;
}

And here is the board class.

public class Board {
    TileSheet sheet;
    TileRenderer renderer;

    Tile[][] tiles;

    Vector2 initPlayerPosition;

    float x = 0;
    float y = 0;

    public float getX()  {
        return x;
    }

    public float getY()  {
        return y;
    }

    public TileSheet getSheet()  {
        return sheet;
    }

    public Tile[][] getTiles()  {
        return tiles;
    }

    public int getWidth()  {
        return tiles[0].length;
    }

    public int getHeight()  {
        return tiles.length;
    }

    public Vector2 getInitPosition()  {
        return initPlayerPosition;
    }

    public Board()  {
    }

    public void loadLevel(String name)  {

        // Temp, the following five lines (including the whitespace) look ugly
        // TODO: Make the map placing dynamic
        this.x = 800 / 2 - (tiles.length * sheet.getTileWidth()) / 2;
        this.y = 20;

        initPlayerPosition.x += this.x;
        initPlayerPosition.y += this.y;
    }

    public void init(GameContainer gameContainer, StateBasedGame game) throws SlickException  {
        Image sheetImg = new Image("data/textures/tileset.png");
        sheet = new TileSheet(sheetImg, 16, 16, 1.0f);

        renderer = new TileRenderer(this);
    }

    public void render(GameContainer gameContainer, StateBasedGame game, Graphics graphics)  {
        renderer.render(tiles, gameContainer, game, graphics);
    }

...

public class Tile  {
    int sheetX;
    int sheetY;

    bool collidable;

    public Tile(int sheetX, int sheetY)  {
        this.sheetX = sheetX;
        this.sheetY = sheetY;

        // If there is nothing (0,0) allow the player to collide
        if (sheetX == 0 &&
            sheetY == 0)  {
           collidable = true;
        }  else  {
           collidable = false;
        }
    }
}

Any ideas?


texts: Why do I get this error about DllMain when using D3D from within a DLL?

texts:
I am trying to create a Dll that will handle all my rendering, I am trying to initialize Direct X but I am getting the following error message:

  DXGI ERROR: CreateDXGIFactory cannot be called from DllMain. [ MISCELLANEOUS ERROR #76: ]
  Exception thrown at 0x00007FF978181F28 in Engine.exe: Microsoft C++ exception: _com_error at memory location 0x000000541631BE90.

I never directly call CreateDXGIFactory, I only call D3D11CreateDevice before the program crashes, here is the code for D3D11CreateDevice:

HRESULT hRes;
    D3D_FEATURE_LEVEL featureLevel;
    m_pConsole->WriteToConsole("Creating D3D11 device !");
    hRes = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, NULL, 0, D3D11_SDK_VERSION, &m_pD3D11Device, &featureLevel, &m_pD3D11DeviceContext);

This function call is not in Dll main it is in an initialize function that is in its own class within the Dll.


texts:
I am using assimp to load 3d model data. I have noticed that each loaded model is made up of different meshes. I was wondering should each mesh have it's own vertex/index buffer or should there just be one for the whole model? From looking through the index data that is loaded it seems to suggest that I will need a vertex buffer per mesh but I'm not 100% sure.
I am using C++ and DirectX9

Thank you,

Mark


texts: Why does setting a static member value in MonoBehaviour child class constructor have no effect?

texts:
I am following a tutorial for Unity. I don't know C# but I know other similar languages.

I got the tutorial to work. Here is the script I used.

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

public class PlayerMove : MonoBehaviour {

    private Rigidbody rb;
    public float speed;

    // Use this for initialization
    void Start () {
        speed = 3.5f;
        rb = GetComponent <Rigidbody> ();
    }

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

        float fx = Input.GetAxis ("Horizontal");
        float fz = Input.GetAxis ("Vertical");

        rb.AddForce (new Vector3 (fx, 0, fz) * speed);
    }
}

This goes slightly against my C++ instincts, which are to put initialization values in a constructor.

    public PlayerMove ()
    {
        speed = 3.5f;
    }

    void Start () {
        rb = GetComponent <Rigidbody> ();
    }

This doesn't work. In Unity, the speed field has an initial value of 0.

Why does setting the initial value in a constructor not work?


texts: Change the colour of all particles on screen

texts: I'm trying to make it so when the user clicks a button, the colour of all particles on screen change to a certain colour. Is there a way to change the colour of all particles on screen coming from the same particle emitter at runtime? I know there is the main module's startColor property, but that only changes the particle colour for new particles, not ones currently on screen. Currently I've tried messing around with the colorOverLifetime module, but I just get these weird blend between the original colour and the new one.


texts:
I'm confused about the usage of trilinear filtering and anisotropic filtering in SharpDX.

As far as i understood, trilinear filtering does linear filtering to the textures and in a case of LOD-change it also interpolates between the too LODs to smooth the transition.

Anisotropic filtering make the texture bigger. Now it is possible to use trilinear filtering to do the same thing, due to anisotropic filtering with bigger textures. This causes a lesser blurred image, when you use anisotropy, because the interpolation is better.

Now, it should be possible to use trilinear filtering and anisotropic filtering at the same time. But in the SamplerState i can only choose  Filter.Anisotropy or Filter.MinMagMipLinear (should be trilinear, right?). You can see all possible filters here: D3D11 Filter Enumeration.

So my question: Can you use both techniques together, if yes, how can i archieve that in SharpDX with SamplerState?


texts: How to export unreal assets in a package like in unity?

texts:
Unity has an asset exporter that export it into a .unitypackage format. This ensure that the prefab has all the links to its child assets.

In Unreal 4, its migrate tool allow for moving of assets. However, it require that both project be on the same machine to migrate from one content folder to another content folder.

How can I export unreal assets for easy sharing in a similar way to unity?


texts: Why does RGB order differ between color formats?

texts:
On the reference page for SurfaceFormat, it indicates that the Bgra4444 format is an unsigned format which is 16-bits long, with 4 bits per color with alpha. Further down the page, it describes the Rgba64 format as being 64-bits long, with 16 bits per color (including alpha).

Why does one format list R-G-B as the color order, while the other lists it as B-G-R? I understand it likely has to do with the underlying hardware, but there certainly needs to be a reason that it wants it in a reversed order for the other format.


texts:
Some background

I've come from the world of web development. And it's a real trending in web to keep whole app's state in single global store (see Redux, discussion about it's benefits).

Basically the main idea it makes the state management more
predictable.

Question

I have no ideas how Redux-like architecture would fit for a game development.
My main fears it's about usage with main loop inside game and of course about performance.

Did anyone use Redux-like store in GD, or it's a common anti-pattern?

Thanks for opinions.

P.S. It's not really matter, but I use libGDX.


texts: How can bays and straits be determined in a procedurally generated map?

texts:
I've got a procedurally generated map using Voronoi cells, with a defined sea level and a believable height map.

So far, I've been successful in labelling certain geographic features: land, ocean, lakes, rivers, estuaries, confluences, mountains, and biomes. Biomes include tundra, boreal forest, grassland, and temperate forest. There are also a couple other biomes there but for my purposes they aren't important right now.

I'd like to label bays, and straits next, but I'm at a loss on how to do this properly. A bay is a recessed, coastal body of water that directly connects to the ocean.

A strait is a naturally formed, narrow waterway that connects two parts of the ocean. Basically, where two pieces of land almost touch and there's ocean on both sides. Also called a "channel".

For determining features, I can loop through any feature by type like this:

for each (var feature:Object in geography.getFeaturesByType(Geography.LAND))
  // loop through lands
  for each (var cell:Cell in feature.cells)
  // loop through cells
    for each (var neighbor:Cell in cell.neighbors)
    // loop through a cell's neighbors
      trace(neighbor.hasFeatureType(Geography.LAND));


texts:
I need to use PlayerPrefs to store arrays of bytes for my game. For some reason, the string I save with PlayerPrefs doesn't come out with the same length.

I.e.

byte[] TestArray = new byte[256];
for (byte i = 0; i < 256; i++)
{
    TestArray[i] = i;
}

char[] charBuffer = new char[TestArray.Length];
for (int i = 0; i < TestArray.Length; i++)
{
    charBuffer[i] = (char)TestArray[i];
}

PlayerPrefs.SetString ("Storage", new string(charBuffer));

PlayerPrefs.Save ();

Debug.Log (new String(charBuffer).Length);
Debug.Log (PlayerPrefs.GetString ("Storage").Length);

Log:

256
5

Is this possibly an issue with encoding? How do I fix it?


texts: Is there an established way to create a 2D XY NavMesh in Unity?

texts:
Specifically, one in the empty space between colliders, rather than on an XZ plane (more or less) over the surface of a collider?

Specifically this is because I have a drone, in a current project, which must follow a target. This target isn't always reachable by shortest-path, and I'm currently experimenting with a number of algorithms to find a way to guide it around obstacles. I am on something of a deadline and would like to minimize my work, if I can.

I recognize that there are cheats around this, like having it magically appear from off-screen at a critical distance. I'm going to implement them in any case, but that's not what this question is about.

Unity's NavMesh tools were initially alluring, but as far as I can tell they seem to require a very specific FPS-like setup for this project, which I am in no way following. This feels unlike Unity Technologies, and particularly short-sighted of them; so before I go further, I would like to verify that I'm interpreting all of this correctly.

For the sake of stability, I would like to avoid hack-around solutions, if possible. All the same, they are welcome.


texts: How can I color a Pygame image surface? I either want to change every pixel that is color A into color B, or else change every pixel into color B. Either works, so long as transparent regions remain the same.


texts: Is it possible to detect a collision between a sprite and a UI image in Unity?

texts:
I have a stationary sprite with the tag "Player" with a Rigidbody2D (dynamic body type and discrete collision detection) and circle collider 2D.

I also have a moving UI image; also with a Rigidbody2D (dynamic body type and discrete collision detection) and circle collider 2D.

I want to detect when the moving UI Image collides with the sprite, however I'm not getting the print statement inside of the OnCollisionEnter2D() function below whenever I see them collide on the screen.

public class MeteorController : MonoBehaviour
{
    float xCoor;
    float yCoor;

    float newXCoor;
    float newYCoor;
    Vector3 newPos;

    float speed = 1.25f;

    // Start is called before the first frame update
    void Start()
    {
        xCoor = transform.localPosition.x;
        yCoor = transform.localPosition.y;

        newXCoor = xCoor * -1;
        newYCoor = yCoor * -1;
        newPos = new Vector3(newXCoor, newYCoor, 0);
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(newPos * Time.deltaTime * speed);
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Player")
        {
            SceneManager.LoadScene("PlanetSpawningTest");
            print("PLAYER");
        }
        else if (coll.gameObject.tag == "Planet")
        {
            print("PLANET");
        }
    }
}


texts: How can I distribute a native executable for a Python program?

texts:
Lately all of my work has been in Python (and Ruby), and I'm in love with those two languages. There are many libraries for game development on Python but the problem I see is that many of those frameworks don't cover the "distribution" aspect of game creation. I'd like to code my game on Python (and any other pure Python extra libraries I need) and be able to distribute an executable for the main PC platforms (Windows, Mac and Linux).

Any options out there or what are the best combinations for this? (maybe pyglet + cx_freeze)


texts: I have an object that has a front collider, left collider and right collider.  When a collision occurs, I notice that there are situations where the front collider and left collider/right collider has collided with the object. I need to somehow figure out which collider made contact "first".  Is there anyway to do this?  The reason I need this is because I have different code that needs to run depending on which collider made contact first.


texts: Playing basic imported animations in UDK

texts:
I'm trying to wrap my head around basic animations in UDK.

I've created a simple turret-like structure in Maya, rigged, skinned, and animated. It has 4 bones. I have done all the steps necessary for exporting and importing as an FBX (baked animations, etc.)

I've imported it into UDK, and can view both the AnimSet and SkeletalMesh in the Content Browser.

The AnimSet Editor previews the animation perfectly. This is a looping animation. I can load the SkeletalMesh into my scene, but I can't figure out how to trigger the animation.

What is the simplest way to trigger this animation at run-time?

I could have it start when the scene loads and loop indefinitely, or I could have it triggered by pressing a switch or using a trigger volume. I just can't figure out how to make that happen.

Also, any resources on diving deeper into this subject would be greatly appreciated as well. Thanks!


texts:
I am using OpenGL ES 2.0
I have a bunch a quads to be drawn, would love to be able to have to pass only 4 vertices per quad as if I were using GL_QUADS, but basically I just want to know the best way of drawing a bunch of separate quads.
So far what I've found I could do:

GL_TRIANGLES(6 vertices per quad)
Degenerate GL_TRIANGLE_STRIP(6 vertices per quad)

Possibilities I've found:

GL_TRIANGLE_STRIPS with a special index value that resets quad strip(this would mean 5 indexes per quad, but I don't think this is possible is OpenGL ES 2.0)


texts: Unity - Renderer "raycasts" from top down?

texts: I'm trying to have objects in a game be selectable only from a top down orthographic camera view. I think having physics colliders might be overkill for that - especially because this only needs to be in 2D and not 3D. Is there another method that might be better, such as something like a renderer "raycasts", but perhaps even more performant as it is just from the orthographic 2D top down view


texts: Unity 3D - Why does my button need to be clicked twice to work?

texts:
My goal is to go back and forth between a series of animations by clicking left and right arrow UI buttons. I wrote this C# script and the "next" button (which executes AddInt() on click) works as intended, however the "previous" button (which calls ReduceInt() on click), needs to be clicked twice to work. Is this a glitch or is something wrong with my code?
public class update_animator_parameter_int : MonoBehaviour
{
    Animator gameobject_animator;
    public string int_parameter;
    public int max_int;
    public int current_int=0;

    void Start(){
        gameobject_animator = GetComponent<Animator>();}

    public void AddInt(){
          current_int++;
          if (current_int > max_int){current_int = 0;}
          gameobject_animator.SetInteger(int_parameter, current_int);}

    public void ReduceInt(){
          current_int--;
          if (current_int < 0){current_int = max_int;}
          gameobject_animator.SetInteger(int_parameter, current_int);}
}