texts: Choosing a heuristic function for RPG character's AI

texts:
I am designing an AI for mouse and cat. So they have HP, and cat will chase and eat mouse, mouse will eat cheese. This eating action will help them to gain HP. If they can't eat food, they will die if they use up all the HP.

So I searched through books and I have a basic algorithm for this.

def chooseAction(actions, goals):
  # Go through each action, and calculate the
  # discontentment.
  bestAction =  actions[0]
  bestValue = calculateDiscontentment(actions[0], goals)
  for action in actions:
    thisValue = calculateDiscontentment(action, goals)
    if thisValue < bestValue:
      bestValue = thisValue
      bestAction = action
  # return the best action
  return bestAction

def calculateDiscontentment(action, goals):
  # Keep a running total
  discontentment = 0
  # Loop through each goal
  for goal in action:
    # Calculate the new value after the action
    newValue = goal.value + action.getGoalChange(goal)
    # Get the discontentment of this value
    discontentment += goal.getDiscontentment(value)

struct Goal:
  value
  def getDiscontentment(newValue):
    return newValue * newValue

This algorithm is quite easy to understand, and quite easy to implement.

So I have to determine Goal and goal value for each action they take.

Let say a mouse, He may want to move, eat.

So I have to come up with a value(wiliness) for these values.

What is a good way to determine these values?

My approach is here.

Ley say my mouse have a view range of 3 cells and it can only walk in four directions up down left and right.

The goal eat value may determine by its MAX_ENERGY and NOW_ENERGY and I come out a formula
eatValue = MAX_ENERGY - NOW_ENERGY. This make sense because, it NOW_ENERGY is equal to MAX_ENERGY, my mouse has a wiliness 0 to eat.

What is a good way of come out this simple formulations?
What will be the good heriustic for my mouse to move?


texts: libgdx game process dies on loading texture atlases

texts:
I try to load a lot of texture atlases (10) with approximately 5 (~2048x~2048)(not using PoT) .pngs each. I'm using AssetManager and there is no trouble with it on my pc but when I try it on my tablet the app just dies without any error messages or crash reports and there aren't any outOfMemoryExceptions.

Here's my log:

DropBox link

the max memory: 67 is

Runtime().getRuntime().maxMemory() / 1000000

I'm running out of ideas of what to do. Maybe I don't fully understand the way mobile games work: is that a lot of atlases (I have other textures not atlases apart from these atlases)? because everything looks quite fine in the memory segment as much as I know. Anyway I'm open to suggestions and maybe some tips. And I'd really like to keep these atlases in my game.

EDIT: the game loads on my tablet but not phone when I use 1 png per atlas (8192x8192) but my tablet doesn't show images larger than 2048x2048 for some reason oh and the images in the atlas aren't even 1024x1024 so idk why it doesn't show them must be because the atlas is 8192x8192.

EDIT #2: I load only atlases now, no separate .png files and I am now using PoT (2048x2048). 17 atlases some have 2 pngs some even have 1 png but there are some that have 5+ and that's my level plus player animations plus I'm using a gradient for my whole level that is ~10000px in width combined and I use FBO to do a Lighten shader on the level and my level has animations. Is that too much? Anyway this time the game died @ 94% on my phone(Galaxy S2) and @ 58% on my tablet(Lenovo IdeaTab A2109) and here's my new log but this time from my phone:

DropBox link log_new

I'm confused because there aren't any outOfMemory exceptions and I'm disposing every possible thing there is to dispose. btw my app in the logs is com.comraz.slashem
Is theree something I can do? f.e. downscale textures or use mipmaps or something? my level textures are 1024x768 when zoomed in and 1024x1536 when zoomed out. If you have any ideas or any questions please do ask or tell me. Oh and my camera size is 1280x768


texts: Why does my model render differently than its preview?

texts:
I've been importing .fbx files that I made with 3DS Max 2012 into Unity, and it's quite neat to see my models running around in game. However, I can't help but notice that the models, as they're rendered in game, vary substantially from what they look like in the preview (and also what they looked like in 3DS Max).

Observe:

           In-Game                   Unity Preview            3DS Max

My gut tells me that I'm not setting up Unity's lighting system properly. What, then, do I need to do, to either my scene or my model, in order to get the left-most picture to look like the middle one?


texts: Unity UI vanishes when the camera Z exceeds 1000

texts:
We are developing 3D racing game.  After the player's position in Z axis reaches 1000, our Canvas UI is hidden and reset.  If I unparent it from Character controller, it still gets auto reset but not hidden.  If I drag player back to < 1000, it again shows my UI.

Any suggestions why this may be happening?


texts:
I'm trying to create a falling word game like z-type (code here). I have created 3 game objects and I want the words to be added as text to these game objects something like a health bar is added to enemies etc. This is the word spawner script that spawns the word on screen.

public GameObject wordPrefab;
public Transform wordCanvas;

public WordDisplay SpawnWord()
{
    Vector3 randomPosition = new Vector3(Random.Range(-2.0f, 2.0f), 7.0f, 0);
    GameObject wordObj = Instantiate(wordPrefab,randomPosition, Quaternion.identity, wordCanvas);
    WordDisplay wordDisplay = wordObj.GetComponent<WordDisplay>();
    return wordDisplay;
}

Right now the words are spawned at a random x position and y position of 7.0. Instead of this how can I assign the words to the gameobjects that I have created.

Edit

I have created a spawner that spawns 3 enemies at the top of the screen and they start falling down to the bottom. Here is the script attached to the enemy game objects:

public float fallSpeed = 1.0f;
public GameObject wordPrefab;
private Transform parent;

public WordDisplay SpawnWord()
{
    Vector3 randomPosition = new Vector3(Random.Range(-2.0f, 2.0f), 7.0f, 0);
    GameObject wordObj = Instantiate(wordPrefab, randomPosition, Quaternion.identity, parent);
    WordDisplay wordDisplay = wordObj.GetComponent<WordDisplay>();
    return wordDisplay;
}

// Update is called once per frame
void Update () {
    transform.Translate(0, -fallSpeed * Time.deltaTime, 0);
}

I have also removed the SpawnWord() method from the wordspawner script. However the words don't spawn along with the enemy gameobjects. There is one more script called the WordTimer. Not sure where to add this code. This is from the original code that's on github.

public WordManager wordManager;
public float delay = 1.5f;
private float nextWord = 0f;

void Update()
{
    if (Time.time >= nextWord)
    {
        wordManager.AddWord();
        nextWord = Time.time + delay;
        delay *= 0.95f;
    }
}


texts: Implementing score relative to total game time

texts:
How would one create score dependent on total time in game? I would like the score to count by 1000+ each second the game is running for. Later I am going to add some coins which will give my total score +1000 also.

How would one create this functionality? This is all I have right now:

  let scoreDisplay = UILabel()
    scoreDisplay.text = "Score: \(self.score)"
    scoreDisplay.textColor = UIColor.red
    scoreDisplay.frame = CGRect(x: mainWidth / 2 - 200, y: mainHeight - 400, width: 247, height: 100)
    self.view.addSubview(scoreDisplay)

    let delay = SKAction.wait(forDuration: 0.25)
    let incrementScore = SKAction.run ({
        self.score = self.score + 1
        self.scoreDisplay.text = "\(self.score)"
    })

I'm pretty new to Swift, so sorry for my basic question!


texts: How to change the way LibGDX scales images?

texts:
I'm using FillViewport and OrthographicCamera. LibGDX is scaling my images rather badly - jagged edges, visible pixels. How can I change the scaling method?

by the way, I'm pretty sure the issue isn't my images. I've scaled them using imaging software and they look a lot better than when LibGDX scales them.


texts:
I am studying Unity, and so far I encountered three different ways to move a character. As far as I understand:

Directly changing the transform  - ignores both physics and colliders;
Using a CharacterController component - ignores physics but considers colliders;
Using a RigidBody component - considers both physics and colliders.

Are these descriptions correct? Which one should I use?


texts: When the player loses all of their lives, I want the entire game screen to go grayscale, but not stop updating immediately. I'd also prefer it fade to grayscale instead of suddenly lose all color. Everything I've found so far is either about taking a screenshot and making it grayscale, or making a specific texture grayscale. Is there a way to change the entire playing field and all objects within to grayscale without iterating through everything?


texts: How to save a character to be used in all Game States?

texts:
I am using C# and SFML.

I am having a problem understanding how to save a character in memory, so I can use the character in any game state.

Right now, the character is a class, and the player creates the character in the "Character Creation" GameState. However the actual variable is created in the GamePlayState class (see below).

class Character : IGameObject
{
    public Vector2f SpritePosition { get; set; }
    public Vector2f SpriteScale { get; set; }
    public string Name { get; set; }

However, I need all of the character data to be usable in any/all Game States.

I tried using a static game container (Dictionary, which held GameObjects- the player's character) but ran into some problems where I couldn't build. So I tried a different method to handle it.

I save all of my GameStates in a Dictionary which resides in the primary game loop.

stateSystem.AddState("Gameplay", new GameplayState(stateSystem));

I can call any specific GameState, but it acts as though the character (if created in Gameplay) cannot be access in other game states. The Game States can, however, access any other Game State.

For example, I tried to create the character in Gameplay - GameState

class GamePlayState : IGameObject
{

Character playerCharacter = new Character();

}

And in the class CharacterCreationState, I try to access that Character. It says "IGameObject does not contain a definition for playerCharacter".

Variable = stateSystem["Gameplay"].playerCharacter.variable;

I even created a function in my StateSYstem class which gets gameobjects.

        public IGameObject getGameObject(string stateID)
    {
        return _stateStore[stateID];
    }

This works to get the correct IGameObject, which would be the Gameplay State.

class GamePlayState : IGameObject
{

Character playerCharacter = new Character();

}

But once i have that IGameObject (the GamePlay Game State) I cannot grab the playerCharacter to manipulate it.

Perhaps I am just tired, but I am having a hard time figuring out how to do this without making the Character playerCharacter a global variable, creating in the main game loop.


texts: Modify the effect of a card being played

texts:
I'm trying to recreate a simple card game. Each played card has an action (draw extra cards, peek at draw stack, eliminate an opponent card, etc). Once played, it goes on a stack, and the card effect is executed in order.

Cards added by effects are added at the end of this stack as well, and executed once it is their turn.

Each player also has a different unique influence on exactly one type of cards that changes the effect (enhances it like draw 4 instead of 2 or taking cards instead of trashing them to graveyard).

So far a card has a simple interface with value, type and doAction. While I could on each card do a check if a player influence would take effect, this seems like a hard coded noodle salad and makes it difficult to add new cards or influences. And more than once influence can take effect on the same card (for example, one effect could be steal 2 instead of 1 and the second effect, you can steal only a certain type of card from a second influence instead of free choice)

I'm looking for a way to react on a method call (played card that gets executed) and change it accordingly. I'm investigating using delegates for this purpose.


texts: Synchronization between several glDispatchCompute with same SSBOs

texts:
Let's say I have one compute shader A which writes to an SSBO, and then a second compute shader B which reads from the same SSBO.

Do I need to do anything special to ensure that A has finished executing before B starts?


texts: Looping world for a top down space shooter?

texts:
I am trying to understand how to make a seamless looping world for my top down space shooter.
First thing I tried was using multiple cameras, and teleporting the player when he reaches the edge, but it is not working well, and I don't like that I have to use 4 cameras.
I wanted to test making the objects in the world teleport around the player, but I will have problems with the fact that each object is a different size, and teleporting them around will for sure create problems with moving objects. (Big obstacles could be teleported away and not collide with, for example, bullets until the bullet gets teleported too but inside the big obstacle)
Are there other ways to accomplish this?
Screen of the game (everything is still a placeholder)
https://i.stack.imgur.com/8FWCE.png


texts: Rotate A towards B with limited turn rate

texts:
I want to rotate A towards B with a fixed turn rate per second.
My math skills are very limited and I have no clue in how to accomplish this.

Best Regards


texts:
I am developing my android game, 2D Sidescroll arcade game, its almost finished, I found artist who wants to cooperate with me, creating graphics for my game, but we have to discuss how much % he will receive if there will be any income from our game.

How do you game developers handle this? What is fair share for an artist? Here is little description on my and his work, to estimate work value:

Done by me:

game idea, story
game code (6 months of development) all game features, everything generally
visual level editor
levels created by me (more than 120)
android license bought be me (I know its cheap but still it is value)
sound purchased by me

Done by artist:

game graphics generally, ground tileset, game characters, 5 tiled monsters (animation), around 30 different graphics for different game objects (like environment elements, obstacles etc)

I would be grateful for some informations, thank you!


texts: Unity 5.1 has integrated VR, its in the Build Player Settings as a checkbox. I want a startup scene that is not VR, then when the user starts it enables the VR camera. Can I do that?


texts: How much longer should I support iPhone 3G?

texts:
I'm in the process of developing and releasing an iOS game, and have found that it just won't run on an iPhone 3G (don't even ask about a 2G) for many reasons.  Primarily, the number of sprites and sounds needed for each level continually cause low memory crashes.  I've already pared it down to the bare minimum and strategically load/unload resources as needed, but some items need to be cached so they can be activated quickly.  My last resort (which I'm trying to avoid) is to make lower quality versions of all audio.  Graphics are already packed tightly into sprite sheets.

The game runs wonderfully on an iPhone 4 and iPad, and even performs nicely on a 3GS.  Should I be concerned about no support for older devices?


texts: How do I pass textures into a fragment shader in Slick?

texts:
I've written a shader that uses three different textures, tex0, tex1, and tex2. I can load it into Slick and successfully display it, but I can't figure out how to set the three different textures. Whichever texture I last load or set is the one used for all three.

My code:

if (sp == null) {
    try {
        sp = ShaderProgram.loadProgram("passthrough.vert", "planet.frag");
        planet = TextureLoader.getTexture("png", new FileInputStream("earth.png"));
        clouds = TextureLoader.getTexture("png", new FileInputStream("clouds.png"));
        lights = TextureLoader.getTexture("png", new FileInputStream("lights.png"));
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

sp.bind();

// Attempt to set tex0-tex2. This fails and just sets everything to tex2.
glUniform1i(sp.getUniform1i("tex0"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, planet.getTextureID());

glUniform1i(sp.getUniform1i("tex1"), 1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, clouds.getTextureID());

glUniform1i(sp.getUniform1i("tex2"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, lights.getTextureID());

sp.setUniform1f("time", tick * 0.03f);
sp.setUniform2f("resolution", 400f, 400f);

// Render a quad. This works, except that the textures are all the same.
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(0, 400);
glVertex2i(400, 400);
glVertex2i(400, 0);
glEnd();


texts: How can I draw outlines around 3D models? I'm referring to something like the effects in a recent Pokemon game, which appear to have a single-pixel outline around them:


texts: XNA shader compiler error in release mode

texts:
I'm having a hard time figuring out if I'm doing something wrong, or if there is a bug with Visual Studio.

I want to pass a float into my pixel shader, clamp it to a value, and then return it as part of the color. Here is my shader code:

float test;

float4 PixelShaderFunction(float2 texCoords:TEXCOORD0) : COLOR0
{
    float n = clamp(test, 0, 1);
    float4 color = float4(n, n, n, 1);

    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

Here is how I'm using the shader:

    protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            simpleEffect.Parameters["test"].SetValue(-1f);
            spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, simpleEffect);
            spriteBatch.Draw(pixelTexture, new Rectangle(10, 10, 100, 100), Color.Red);
            spriteBatch.End();

            base.Draw(gameTime);
        }

The shader compiles fine when Visual Studio is set to Debug mode, but when I set it to Release, it gives me the following error (Please excuse the ShaderModel3Bug solution name... I get the same error with both shader model 2 and 3):

Error   1   Errors compiling E:\_C#\ShaderModel3Bug\ShaderModel3Bug\ShaderModel3BugContent\simple.fx:
(15,23): ID3DXEffectCompiler::CompileEffect: There was an error compiling expression
ID3DXEffectCompiler: Compilation failed E:\_C#\ShaderModel3Bug\ShaderModel3Bug\ShaderModel3BugContent\simple.fx 15  23  ShaderModel3Bug

Line 15 of the shader is this:

PixelShader = compile ps_2_0 PixelShaderFunction();

I have tried compiling the shader directly using fxc.exe that comes with the June 2010 DirectX SDK. Using the command fxc.exe /T fx_2_0 E:\_C#\ShaderModel3Bug\ShaderModel3Bug\ShaderModel3BugContent\simple.fx /Fc:output.fxc, I get:

Microsoft (R) Direct3D Shader Compiler 9.29.952.3111
Copyright (C) Microsoft Corporation 2002-2009. All rights reserved.

compilation succeeded; see C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Utilities\bin\x64\output.fxc

So my question is, why can't Visual Studio compile the .fx file in Release mode? Am I doing something I shouldn't be doing?

Update

Apparently XNA Game Studio doesn't use the latest version of fxc. I downloaded the March 2009 DirectX SDK, and the compilation fails with the same generic error message as Visual Studio:

C:\Program Files (x86)\Microsoft DirectX SDK (March 2009)\Utilities\bin\x64\ps.fx(16,23): ID3DXEffectCompiler::CompileEffect: There was an error compiling expression
ID3DXEffectCompiler: Compilation failed

compilation failed; no code produced

If I run the March 2009 version of fxc.exe with the /Op (disable preshaders) flag, it compiles successfully... I am still not sure what version of fxc xna uses, or what I need to do to get my shader to compile in release mode. Any help would be appreciated.


texts: Distant objects remain fully lit at sunset, when they should be in the mountain's shadow

texts: I'm trying to make dynamic sunrises and sunsets in my game but I have some problems. My scene is surrounded by mountains and when the sun tint is still hot the sun is not visible but, the trees that are far from the player (Around 100 meters) are lighted like if the mountains are not casting shadows, and when I get closer to theses trees they become black as they should be. If I extend the shadows distance it changes nothing. Also, when the sunrise, even if it should not be visible it should do some ambient lighting, but everything is totally black except some trees.


texts:
I'm making a 2D shmup with XNA 4.0 and one of the weapons in the game that I want is a laser beam that follows a path or a series of points and will smoothly beam along the path.

How would I go about achieving this?


texts: Platformer gravity where gravity is greater than tile size

texts:
I am making a simple grid-tile-based platformer with basic physics.

I have 16px tiles, and after playing with gravity it seems that to get a nice quick Mario-like jump feel, the player ends up moving faster than 16px per second at the ground.

The problem is that they clip through the first layer of tiles before collisions being detected. Then when I move the player to the top of the colliding tile, they move to the bottom-most tile.

I have tried limiting their maximum velocity to be less than 16px but it does not look right.

Are there any standard approaches to solving this?  Thanks.


texts: How is a Game Manager supposed to be constructed?

texts:
I'm a beginner developing games on Unity3D and now that I've become a little bit familiar with GameManagers I've been wondering about certain aspects.

How do you contruct a GameManager in the most efficient way? Since it's an entity that persists through scene loads, it has to be tweaked to reset some values on level load because it doesn't do that by itself.

I'm making a 2D platformer, so when a new level is loaded (or the current level is restarted) the GameManager has to dynamically find references to the objects it handles. And because each level cannot be identical to the next, should I have code in the GameManager to find references to the specific GameObjects and values depending on the level? I'm thinking something like this:

public class GameManager : MonoBehaviour {

  //Values and core methods etc

  void OnLevelWasLoaded(int level) {
    if (level == 1) {
      //Find references and set values for level 1
    }
    if (level == 2) {
      //Find references and set values for level 2
    }
  }
}

Or should I have a separate GameManager for values, game states and events and an in-between script for handling the GameObject references? I just want to learn this right. I'm worrying that if I dump "everything" in the GameManager, it becomes too big and inefficient.

Speaking of which, is it OK for the GameManager to also handle the UI/HUD? Or should there be a separate UIManager dedicated for this task?


texts:
Is it possible to setup something sort of like a class in C++ but in c in the simplest terms? I want to avoid using c++ but I would like to create a simple struct that has glsl shader program.

for example

struct shader_program
{
     GLuint shader;
     void (*create_shader)(const char* vss, const char* fss);
     void (*enableShader)(void);
     GLuint (*getUniformLoc(struct shader_program* sp, char* name);
     void (*disableShader)(void);

}

sample usage.

struct shader_program simple_shader = create_shader(.., ..);
struct shader_program advanced_shader = create_shader(.., ..);

draaw()
{
 simple_shader->enableShader();
 //...bind vai, draw, etc..
 simple_shader->disableShader();

 advanced_shader->enableShader();
 //draw
 advanced_shader->disableShader();

}

the main question is how would i set this up in a header and source file so that I can use a struct like this to do my rendering?


texts: How to randomly create a fair maze for a multiplayer game?

texts:
I am creating a 2d multiplayer RTS game which happens inside a maze. I have used Growing Tree algorithm to randomly generate the maze. I thought that the maze would be fair for each team as long as each team's shortest path to solving the maze is equal to the other team. I made sure of that by making a rule in my game which dictates that each team start point is the other team's finish point and vice versa, so the shortest path would always be equal for both teams. but in practice, I noticed something else.

this question sprang up on me when I was trying to make the resulting perfect maze to a non-perfect maze using this solution, specifically @tobias-k answer.

  if you already have a maze with a single path form start to goal, use this variant:

  Do a Breadth First Search from both the start and the goal, and for each cell in the maze record the number of steps that cell is away
  from both the start and the goal.
  Subdivide the maze by putting all cells that are closer to the start into the start set and all cells that are closer to the goal
  into the goal set.
  Remove a wall between the two regions to add an additional path from start to goal.

  The generated paths might have (maybe even substantial) parts in
  common, but they should be unique loop-free paths from start to goal.
  Here's an illustration of the first case:

  the result of seperating the maze according to each cell distance
  from start or end point

However, when I use BFS to calculate all distances from my start and finish point, and before removing a wall to create a non-perfect maze, I mostly get something like this:

in this picture, 336 cells are closer to team Red start point and only 105 are closer to Team Blue start point.
Even removing a wall (or more than just one wall) between these two sections does not help the situation.

My game is about collecting the treasures that are randomly spread throughout the maze and getting out before the other team exits the maze, this resulting mazes are totally unfair because it gives one team the higher chance of reaching more treasures in the maze sooner compared to the other team.

so my qustions are:

Does the mentioned results of growing tree maze generator means that the maze is not fair for a multiplayer game (for simplicity lets just imagine the game happens between two players)?
Do I need to change my maze generator to something that produces a uniform texture, like Wilson's or Aldous-Broder Algorithm? (this is based on algorithms introduced by Astrolog


texts:
I want from my script to change the color of the button that identify from the Function OnClick. It's possible ?

public float Money;
public GameObject[] upgrade_health_level;
public int[] Player1_heal;

void Start()
{
    Money = 60;
    Player1_heal = new int[6];

}

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

} // END UPDATE

public void upgrade_HEAL() // button OnClick
{

        if (Player1_heal[0] == 0 && Money >= 10)
        {
            Money -= 10;
            Player1_heal[0]++;
            upgrade_health_level[0].transform.localPosition = new Vector3(10, 0, 0);
        }
        else if (Player1_heal[0] == 1 && Money >= 10)
        {
            Money -= 10;
            Player1_heal[0]++;
            upgrade_health_level[0].transform.localPosition = new Vector3(20, 0, 0);
            // Change the button color that use this function
        }

}


texts:
I recently released my first game - solitaire for ios.

What the best way to monetize game?

Options I have in mind:

In-app purchase themes (cards, backgrounds etc...)
Ads subscription (remove ads)
Limited number of games which can be played in certain
period of time with possibility to buy “life”.
Paid return (back) button.

Thank you in advance!


texts:
I'm trying to make a moving platform move at a constant speed and then when it is near the target start to slow down, I have trying to do this with Lerp, but I'm not satisfied with the results because of two reasons: it goes way too fast between targets, and way too slow near targets.

Also, when it reaches a target it immediately boosts off in the opposite direction. What I want to achieve is for the platform to move steadily between targets, decelerate near targets, and when reaching a target start to accelerate back to the steady speed.

What is the best way for achieving this? Lerp, Smoothstep, other? Thanks! (I'm using Unity)

My current solution:

 _dVeloctiy = _velocity * Time.fixedDeltaTime;
 Vector3 newPosition = Vector3.Lerp(_rigidBody.position, currentTargetPosition, _dVeloctiy.magnitude);
  _rigidBody.MovePosition(newPosition);

  Vector3 dPosition = _rigidBody.position - currentTargetPosition;

  if (dPosition.magnitude > 0.05f)
  {
      _isTurning = false;
  }

  if (dPosition.magnitude < 0.05f && !_isTurning)
  {
      currentTargetPosition = (currentTargetPosition == targetPosition1 ? targetPosition2 : targetPosition1);
      _isTurning = true;
  }


texts: Button not clickable if it's under a Content Size Fitter + Horizontal Layout Group in Unity?

texts:
I'd like to make a Tooltip System/Tutorial System.
I'm using the Content Size Fitter and Horizontal Layout Group components to have a dynamic text bubble..
Also I'd like to attach a button to it,

so when the tooltip appears, the game pauses,

and then when the player clicks the button, it closes the tutorial text, resuming the flow of the game.

But for some reason the click doesn't reach the component. Not even the animation happen, like something is blocking my button from being clicked.
Hierarchy:

uiTutorialText

Has a CanvasGroup to fade the whole structure.

Interactable = true, BlocksRaycast = false

TutorialText

Has an Image (background)

RaycastTarget = false

Has a Content Size Fitter and a Horizontal Layout Group

And Text and Button are just simple plain Text and Button objects, and the Button's Interactable is true.
I also tried making the Button a child of Text, and then translating it sideways, so the button doesn't share screen space with the tooltip. But it's not clickable this way as well.
As soon as I move the Button out of the hierarchy, like directly under the canvas, it works.


texts: How does changing weapons and character animation in 2d games work?

texts: I know how I can make my character move by changing animation-frames. What if I want to use a weapon database? I want the character to fight with a bow and sometimes with an axe (different moves). Do I need like many pictures/animations for every different kind of weapon (bows, swords)? Or am I totally wrong?


texts: What advantage do OpenGL, SFML and SDL have over software rendering?

texts:
I started watching the Handmade Hero stream, where Casey Muratori creates a game engine without using frameworks or such.
Yesterday I got to the part where he showed how an image is drawn onto the screen. As far as I understood it he just allocated some memory as big as the size of the screen he wants to draw to. And then he created a bitmap which he passed to the buffer memory he allocated and drew it to the screen using a os specific function.

This seems quite straight forward. I used GameMaker, changed to Love2D, worked a little bit with Sprite Kit but I was always wondering what was really happening beneath this sometimes confusing layers.

Given that, why even bother using graphics libraries (OpenGL, SFML, SDL, …) when all you have to do is simply allocate some buffer, pass a bitmap and draw it to the screen?

If you then want to draw distinct things to you screen you just write them to your bitmap which then gets passed into the buffer. I'm quite new to programming, but this seems quite simple to me. Please correct me if I'm wrong.


texts:
I start using multisampling by doing

        ContextAttribs attribs = new ContextAttribs(3, 3).withForwardCompatible(true).withProfileCore(true);
        Display.create(new PixelFormat().withSamples(8), attribs);
        GL11.glEnable(GL13.GL_MULTISAMPLE);

How would I reset how many samples it uses?


texts:
All my models are see through and I can't figure out why. For example:

Here's what it looks like when you are not looking through them:

And when I look through one of them:

Why can I see the black cube through the other Model? It's the same the other way around. I can see the gray object through the black cube. I draw the models like this:

public void Draw(GraphicsDevice graphicsDevice)
{
    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.View = camera.View;
            effect.World = worldMatrix;
            effect.Projection = camera.Projection;

            mesh.Draw();

            // Debug: Draw bounding boxes
            modelBox.Draw(effect, camera.View, camera.Projection, effect.World, graphicsDevice);
        }
    }
}

What am I doing wrong?

More screenshots: http://imgur.com/qRA34Ul, http://imgur.com/K4PGWfL


texts: Lightmap not moving properly with camera movement

texts:
I´ve implemented a 2d lighting system (also with support of 2d shadows). Everything was fine until today when I realised that its not working when moving the camera, as it looks like the lightmap has still some offset than the camera position (for example, if camera.x is 100, the lightmap is x=-200)

Little video showing the problem :
Video

I can post any piece of code, for now Im sending you my light shader(fragment)

#version 440

in vec4 fragmentColor;
in vec2 TexCoords;

out vec4 color;

uniform float ambientStrength;

uniform vec2 resolution;
uniform sampler2D textureSampler;
uniform sampler2D lightMapTexture;

uniform bool textureON;

void main(){

    //Calc the ligthMap
    vec2 lightCoord = (gl_FragCoord.xy / resolution);
    vec4 lightMap = texture(lightMapTexture,lightCoord);

    if (textureON){

        vec4 textureColor =  texture(textureSampler, TexCoords);

        vec4 finalColor = lightMap * textureColor * fragmentColor;
        color =  vec4(finalColor.rgb,textureColor.a* fragmentColor.a);

    } else {

        color = fragmentColor;
    }
}

Vertex

#version 440

in vec3 vertexPosition;
in vec4 vertexColor;
in vec2 vertexUV;

out vec4 fragmentColor;
out vec2 TexCoords;

uniform mat4 Projection;
uniform mat4 View;
uniform mat4 Model;

void main(){

    gl_Position = Projection * View * Model * vec4(vertexPosition.xy,0,1);

    fragmentColor = vertexColor;

    TexCoords = vec2(vertexUV.x, 1.0 - vertexUV.y);
}

At first I thought that its a problem with resolution, but everything is good. Everything is working fine until I move the camera(or change its position from 0,0 to something else - all other objects have good position, also mouse coords)


texts: help with shooting projectile along a curve path

texts:
so i been trying to find a way to shoot projectiles along a curve path . and i found this tutorial on youtube which was really good.

i also uploaded the project in case you wanted to check it out. here

but there is problem with this script .if i move the target object somewhere above the starting point the curved path will be diapered and i get couple of errors.in fact when ever the path is about to become a straight line the errors will pop up . here is the screenshot of errors

 and here is a gif file to show when the problem shows up

and finally here is the code responsible for calculating the curve path a lunching projectiles.

 public Transform startPoint;
 public Transform target;
 public int resolution = 30;
 public float curveHight = 25;
 public float gravity = -18;

 public Rigidbody bullet;
 public LineRenderer lineRenderer;
 void Start()
 {

 }

 void Update() {

     DrawPath();

     if (Input.GetKeyDown(KeyCode.Space))
     {
         Launch();
     }

 }

 void Launch()
 {

     Rigidbody clone = Instantiate(bullet, startPoint.position, Quaternion.identity);

     Physics.gravity = Vector3.up * gravity;

     clone.velocity = CalculateLaunchData().initialVelocity;
 }

 LaunchData CalculateLaunchData()
 {
     float displacementY = target.position.y - startPoint.position.y;
     Vector3 displacementXZ = new Vector3(target.position.x - startPoint.position.x, 0, target.position.z - startPoint.position.z);
     float time = Mathf.Sqrt(-2 * curveHight / gravity) + Mathf.Sqrt(2 * (displacementY - curveHight) / gravity);
     Vector3 velocityY = Vector3.up * Mathf.Sqrt(-2 * gravity * curveHight);
     Vector3 velocityXZ = displacementXZ / time;

     return new LaunchData(velocityXZ + velocityY * -Mathf.Sign(gravity), time);
 }

 void DrawPath()
 {
     LaunchData launchData = CalculateLaunchData();
     Vector3 previousDrawPoint = startPoint.position;

     for (int i = 1; i <= resolution; i++)
     {
         float simulationTime = i / (float)resolution * launchData.timeToTarget;
         Vector3 displacement = launchData.initialVelocity * simulationTime + Vector3.up * gravity * simulationTime * simulationTime / 2f;
         Vector3 drawPoint = startPoint.position + displacement;
         Debug.DrawLine(previousDrawPoint, drawPoint, Color.green);

         previousDrawPoint = drawPoint;

         lineRenderer.positionCount = resolution;

         lineRenderer.SetPosition(i - 1, drawPoint);
     }
 }

 struct LaunchData
 {
     public readonly Vector3 initialVelocity;
     public readonly float timeToTarget;

     public LaunchData(Vector3 initialVelocity, float timeToTarget)
     {
         this.initialVelocity = initialVelocity;
         this.timeToTarget = timeToTarget;
     } }}

so,any idea what might be causing the the problem?


texts:
I am having a problem with making duplicates of my AI. When one is within range, it performs normally. If two are in range, then they both freeze up. The AI are direct duplicates of each other. I don't know what causes this. Code
below:

Any help is seriously appreciated. Thank you.

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

public class NavMeshAI : MonoBehaviour {
public Transform player;
public Transform head;
public Animator anim;
public bool pursuing = false;
public NavMeshAgent navComponent;
public Transform enemy;

// Use this for initialization
void Start () {
    anim = GetComponent<Animator> ();
    navComponent = this.gameObject.GetComponent<NavMeshAgent>();
}

// Update is called once per frame
void Update () {
    Vector3 direction = player.position - this.transform.position;
    direction.y = 0;

    float angle = Vector3.Angle (direction, head.up);

    if (Vector3.Distance (player.position, this.transform.position) < 10 && (angle < 360 || pursuing)) {

        pursuing = true;
        this.transform.rotation = Quaternion.Slerp (this.transform.rotation, Quaternion.LookRotation (direction), 0.1f);

        anim.SetBool ("isIdle", false);
        if (direction.magnitude > 2) {
            this.transform.Translate (0, 0, 0.05f);
            anim.SetBool ("isWalking", true);
            anim.SetBool ("isAttacking", false);
            if (pursuing == true) {
                navComponent.SetDestination (player.position);
            }
            } else {
            anim.SetBool ("isAttacking", true);
            anim.SetBool ("isWalking", false);
        }
    } else {
        anim.SetBool ("isIdle", true);
        anim.SetBool ("isWalking", false);
        anim.SetBool ("isAttacking", false);
        pursuing = false;
        navComponent.SetDestination (enemy.position);
    }
}


texts: Transform.position is being changed, but character is not moving back to it when told

texts:
I'm trying to make a respawn point for my car to jump back to if it presses a button. I can see, using the Print() lines, that all the variables are correct and the methods are being triggered when expected.

But the car doesn't go back to the spawnpoint like I want it to. The velocity part seems to take effect and work ok, but the rotation and position part does nothing.

I tried several different variations of this code (ie. GetComponent<> and setting a public player variable (even though I am already in the player with this script)).

Like I said I tried making a public Player and setting the transform p and r on that. I also tried GetComponentByParent<Transform> and setting like that. I've tried a few other variations of that too. And I get the same results.

Here is the bit of code I think is relevant, if you actually need to see more please let me know.

public void OnTriggerExit(Collider other)
{
    if (other.gameObject.tag == "RespawnTrack")
    {
        print("respawn point added upon Trigger Exit");
        recordedTransformAtRespawnTrack = transform;
        recordedVelocityAtRespawnTrack = rb.velocity * 0.25f;
        print("rotation was: X,Y,Z=" + recordedTransformAtRespawnTrack.rotation.x + " , " + recordedTransformAtRespawnTrack.rotation.y + " , " + recordedTransformAtRespawnTrack.rotation.z);
        print("position was: X,Y,Z=" + recordedTransformAtRespawnTrack.position.x + " , " + recordedTransformAtRespawnTrack.position.y + " , " + recordedTransformAtRespawnTrack.position.z);
    }
}

public void CheckToRespawnCar()
{
    if (isRacing)
    {

        if (CrossPlatformInputManager.GetButtonDown("Jump"))
        {
            print("RESPAWN TRIGGERED BY PRESSING BUTTON");

            transform.position = recordedTransformAtRespawnTrack.position;
            transform.rotation = recordedTransformAtRespawnTrack.rotation;

            rb.velocity = recordedVelocityAtRespawnTrack;

        }

    }
}


texts: CubeMap - Why size of skybox cube has no effect?

texts:
I have normal skybox via CubeMap, but i noticed that the size of the cube has no effect. I would expect that when i have cube size 20.0, i will see different result than with cube of size 1000.0 (same as if you have texture 20x20 on 20x20 face and on 1000x1000 face).

It is probably because the CubeMap works somehow different, but i don't know where to find how.


texts: I found a game with the same name as mine! What should I do?

texts:
I published my game Eyeroller on Google Play the other day. I checked there was no game on Google Play with the same name. But today I searched for "eyeroller" on Google (Yes, I should have done it a long time ago) and realized there is a game named eyeRoller on the AppStore. They are completely different games, as you can see.

What are the legal implications of this? Can things like trademarks and copyrights be a problem? Should I change my game's name?


texts:
For a hobby project of mine I have created a finite voxel world (similar to Minecraft), but as I said, mine is finite. When you reach the edge of it, you are sent to the other side. That is all working fine along with rendering the far side of the map, but I want to be able to render this grid as a sphere.

Looking down from above, the world is a square. I basically want to be able to represent a portion of that square as a sphere, as if you were looking at a planet. Right now I am experimenting with taking a circular section of the map, and rendering that, but it look to flat (no curvature around the edges).

My question then, is what would be the best way to add some curvature to the edges of a 2d circle to make it look like a hemisphere. However, I am not overly attached to this implementation so if somebody has some other idea for representing the square as a planet, I am all ears.


texts:
When rendering a camera to a render texture (for a portal effect), it seems to under certain circumstances skip rendering the red channel entirely.
I cannot put my finger on why this might be happening at all. It seems to depend on the angle of the camera, as it stays color-shifted (or not) if I keep the camera in the same position/rotation.
As can be seen in the below pictures, the camera preview does in fact pick up on the full color.
If it is perhaps relevant, I am working in the URP with HDR enabled.
EDIT: Upon further investigation, it seems it can actually skip any channel, it just does red far more often. I just ran into a case where only the green channel was rendered...
It appears to be linked to being forced to render HDR color, for whatever reason?


texts: Effective way of transferring data to HLSL shader in MonoGame and storing it

texts:
I'm toying around with HLSL shaders in monogame. Lets say I want to use a structure in my shader which is like this:

struct Light
{
    float2 pos;
    float  intensity;
};

I'm going to use a varying amount of these Light objects in each frame draw call.

In what kind of structure/array should I store my Light objects in my shader? If I understand correctly I can declare an array like this:Light lights[n];, however n needs to be known at compile time. I can declare a stupidly large array and fill it with some default initialized garbage that I can check for, however this seems very inefficient.
Can I use constant buffers to alleviate my pain? This question makes it seem like it would be an efficient way of transferring and using data on the GPU (I have some CUDA experience, so I know about constant memory and such), but I can't wrap my head around how to use them in this case.


texts:
Im currently using the Andengine GLES20 branch. I know that the new Box2D method setGravity() isn't implemented yet.

Has anyone managed yet to get it to work with Andengine or to write a method which does the same? I really need this new feature of Box2D.

Thank you in advance.


texts: camera.render reads a file in the middle of a gameplay

texts: Why does camera.render read a file in the middle of a gameplay? This causes a lag in my game:


texts: How can I legally allow modders to use my tools that are dependent on licensed assets?

texts:
I am making a moddable game with Unity. I actually have working system for serializing/deserializing items etc.
For purpose of easy item creation in Unity, I made editor-only windows that help you with process of creating objects and setting their properties. The thing is these windows are dependent on bought asset.
My question is how to let users create their own items with those editor-only windows? I wanted to make project open source (so they can put it in Unity and just do it as I did) but obviously I can't put licensed files there.


texts: How to move an object in a heart shape pattern in javascript?

texts: How can I move an object in a heart shaped pattern? I have a move(x, y) function that I can use to move the object, but how to I make a function that will move the object in a heart shaped pattern, with something like a setInterval?


texts: With what structure do you manage the graphics of a game?

texts:
Im currently trying to program a little game (in Java - Libgdx; if thats necessary).

I currently use a GameWorld and a GameRenderer, the GameRenderer just getting all the info it needs from the GameWorld object and calling a method for every different class there is (for example drawPlayer(), drawWorld() etc.).

Should I let my actors draw themselves or encapsulate the data inside of another class and then pass an object of it to the GameRenderer?


texts: "error CS0246: The type or namespace "NAMESPACE" could not be found" while declaring that namespace usage

texts:
I have two scripts, one is located at:

  Assets / Scriptable Objects / ...

while the other one is located at:

  Assets / Scripts / ...

I have the first script encapsulated on a namespace.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using VoidlessNodes.LevelFlowNodes;

namespace VoidlessUtilities
{
[CreateAssetMenu]
public class LevelFlowData : BaseNodeEditorData<BaseLevelNode, LevelFlowEditorAttributes>
{
    private const string MENU_ITEM_PATH = "Create / ScriptableObjects / LevelFlowData";
    private const string NEW_ASSET_PATH = "ScriptableObjects / Level Flow Data";

    [SerializeField] private string _name;
    private RootLevelNode _root;

    /// Gets and Sets name property.
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }

    /// Gets and Sets root property.
    public RootLevelNode root
    {
        get { return _root; }
        set { _root = value; }
    }

    [MenuItem(MENU_ITEM_PATH)]
    public static void CreateAsset()
    {
        LevelFlowData scriptableObject = ScriptableObject.CreateInstance<LevelFlowData>() as LevelFlowData;
        AssetDatabase.CreateAsset(scriptableObject, AssetDatabase.GenerateUniqueAssetPath(NEW_ASSET_PATH));
    }

    public BaseLevelFlowNode GetLevelFlow()
    {
        BaseLevelFlowNode rootLevelFlow = null;

        if(root != null)
        {
            rootLevelFlow = root.GetNode();
        }
        else
        {
            Debug.LogError("[LevelFlowData] Data has no RootLevelFlowNode saved");
        }

        return rootLevelFlow as RootLevelFlowNode;
    }
}
}

And the other one is using the same namespace, which is a namespace I use for my custom scripts, but the only difference is that LevelFlowData's location is not under Scripts.

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

public class TestLevelController : Singleton<TestLevelController>
{
    [SerializeField] private LevelFlowData _levelFlowData;
    [SerializeField] private List<GameObject> _testViews;

    /// Gets and Sets levelFlowData property.
    public LevelFlowData levelFlowData
    {
        get { return _levelFlowData; }
        protected set { _levelFlowData = value; }
    }

    /// Gets and Sets testViews property.
    public List<GameObject> testViews
    {
        get { return _testViews; }
        set { _testViews = value; }
    }

#region UnityMethods:
    void OnEnable()
    {
        BaseInteractable.onTriggeredEvent += (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }

    void OnDisable()
    {
        BaseInteractable.onTriggeredEvent -= (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }

    /// TestLevelController's' instance initialization.
    void Awake()
    {

    }

    /// TestLevelController's starting actions before 1st Update frame.
    void Start ()
    {

    }

    /// TestLevelController's tick at each frame.
    void Update ()
    {

    }
#endregion

#region PublicMethods:
    public void EnableView(int _index)
    {
        testViews.SetAllActive(false);
        testViews[_index].SetActive(true);
    }
#endregion

#region PrivateMethods:

#endregion
}

Do I need to move LevelFlowData to Scripts, and make platform independet compilation (e.g., #if UNITY_EDITOR) encapsulation for UnityEditor namespace usage? Or is there another point I am missing?

This is the specific error log:

  Assets/Scripts/Scene Controllers/TestLevelController.cs(10,27): error CS0246: The type or namespace name `LevelFlowData' could not be found. Are you missing an assembly reference?

Thanks in advance.


texts: How do I combine matrix transformation with non-uniform screen scaling in Flash?

texts:
I'm using a Flash transformation matrix for affine transformation.

I have a rectangular image being rotated and scaled (in 2D). There are two sets of scaling variables, ScreenScaleX and ScreenScaleY, and ScaleX and ScaleY, as well as a counter-clockwise rotation angle, theta. ScreenScaleX and ScreenScaleY are the scaling factors of the window; they should be applied in directions of the original X and Y axes after rotating the image. ScaleX and ScaleY should be applied in the new X and Y directions after rotating the image.

For example: if theta is 90 degrees, ScreenScaleX and ScreenScaleY will still stretch in the direction of the original X/Y axes, but now ScaleY will stretch in the screen's X direction, and ScaleX will stretch in the screen's Y direction.

I think I can accomplish this with some combination of scaling, rotation, and skewing, but I'm struggling to figure out what the matrix would look like. How would I construct a matrix from these variables in order to perform this transformation?


texts: Implementing attack animation in four direction movement

texts:
The way the program is supposed to run is basically, a character can be running/idle and if spacebar is pressed, all movement stops and movement controls are locked through the bool "canMove". The integer shockwave is a 1-4, directly correlating to the direction 1-4 (1 = north, 2 = east, 3 = south, 4 = west). Then, the animation plays and when it is over the controls are unlocked and you can move freely.

The problem I have encountered is, I can find no way to specifically tell when the animation is ending inside of a blend tree. I cannot find a way to allow the animation to play, and then continue to unlock the controls.

Since this site won't let me post more than three links, I will have to describe the animator window. Basically I have four idle states (N, E, S, W). Each motion is a blend tree, and each state is connected with a transition purely based off of int direction.

This is where I tried adding another motion to the blend tree called shockwave, based on threshold speed (-1). This worked up until the point that I realized I would not be able to add anymore attacks or states, and that I could not tell when the animation had finished in order to unlock the controls.

void Update (){

    if (Input.GetKey (KeyCode.Space)){

        canMove = false;
        direction = animator.GetInteger ("Direction");
        animator.SetFloat ("Speed", 0.0f);

        if (direction == 1){
            animator.SetInteger("Shockwave", 1);
            animator.SetFloat ("Speed", -1.0f);

            //find a way to detect that the attack animation is done.
            //continue and allow movement
            canMove = true;

                }
            }

        else if (direction == 2){
            animator.SetInteger ("Shockwave", 2);
            //if(!anim.IsPlaying ("character_shockwave_2")){
                //canMove = true;
            //}
        }
        else if (direction == 3){
            animator.SetInteger ("Shockwave", 3);
            //if(!anim.IsPlaying("character_shockwave_3")){
            //  canMove = true;
            //}
        }
        else if (direction == 4){
            animator.SetInteger ("Shockwave", 4);
            //if(!anim.IsPlaying("character_shockwave_4")){
                //canMove = true;
            //}
        }

Attempted solutions:

I have tried to use waitforseconds(x), and just wait for the attack animation to finish, and then after that amount of seconds I would set the canMove bool to true. For whatever reason, I cannot get this to work.

I have also tried to directly find if the animation is done playing through a few different ways, but I learned that the blend tree does not allow this.

The only solution I have thought might work is actually manually playing all animations through code alone. (Would require re writing the entire program).

If any further code is needed, I can supply it.


texts: Do I need a UPC barcode to sell my game?

texts: Is it necessary to register a Universal Product Code for a video game intended for sale offline? What about online?


texts: How can I iterate over all entities with a particular component?

texts:
I'm currently designing a game engine and want to implement my own ECS implementation, so I decided to look around for ideas.

Unity has recently updated their engine and seems to be pushing towards using ECS, instead of their original components-are-systems design.

I noticed that Unity has a method called "GetEntities", a generic method which can do something like this:

public struct SomeComponent : IEntityComponent
{
    public string Message = "Hello, World!";
}

public struct Filter
{
    SomeComponent someComponent;
}

public MovementSystem : EntitySystem
{
    public override Process()
    {
        // How can I accomplish something like this?
        foreach(var entity in GetEntities<Filter>())
        {
            Console.WriteLine(entity.someComponent.Message);
        }
    }
}

I like this style of iterating over entities, given a filter for a specific component they need to include. But I'm not sure how to accomplish something like this.

If someone could shed some light on how something like this is even possible in C# that would be great!


texts: LibGDX - i need an event like mouseMoved but it shouldn't care about which buttons are pressed

texts: Using ClickListener I have events like enter(), exit(), and mouseMoved(). But when I have any mouse buttons pressed, moveMoved() won't fire because that's how it works. There is touchDragged() but this will only fire if touchDown happened on Actor (or Actor's tap square). I'd like an event that would fire even if any mouse buttons was pressed outside Actor and his tap square, and keep firing each time mouse is moved over the Actor. How to do it?


texts:
I've been using SDL 1.2.14 for awhile without using many of the features from newer OpenGL versions. I'm now interested working only with the 3.3 API (not using the deprecated functions, etc... that's the latest my graphics card supports), but I'm having trouble getting set up.

Here's some information about my development environment:

Windows 7 64 bit
Eclipse Helios CDT
Mingw Toolchain
C++

I've tried building SDL 1.3 and following this tutorial. This ended up being a pretty big pain and I gave up amid a stream of compile errors - I'd prefer to not go this route if possible. I know also that GLEW/GLEE or some do-it-yourself extension function pointers will be required.

So basically: is it possible? If so, what is the best/easiest way to make it happen? Thanks!


texts: Separating lighting for interior & exterior parts of a scene

texts:
I want outdoor areas connected with indoor areas. I use the default setup in Unity.
But as you see in image, indoor point light affects the outdoor area (through the walls) and the skybox does more environment illumination in the indoor area.

How to fix that?

So, I want a skybox that only affects outdoor areas, and point lights that only affect interior areas.


texts: Launch event at the end of an animation with phaser 3

texts:
I'm starting to develop in Phaser 3, and I'm really a begginer.
I'm trying to make an attack move of an archer sprite, but I cannot make it work right...
This is how I have defined the things related to combat:
class Jugador extends Phaser.Physics.Arcade.Sprite {

    constructor(escena, x, y) {
        super(escena, x, y, "jugador");
        this.escena = escena;
        this.escena.add.existing(this);
        this.escena.physics.add.existing(this);

        this.createVariables();
        this.createControls();
        this.createAnimations();
  }

  createAnimations(){
    this.defineAttackAnimation();
    /// Some others...
  }

  defineAttackAnimation(){
    this.attackAnimation = {};
    this.attackAnimation.key = "attack";
    this.attackAnimation.frames =
      this.escena.anims.generateFrameNames("attack",
      {
        prefix: "attack",
        start: 1,
        end: 6
      });
    this.attackAnimation.frameRate = this.attackFrameRate;
    this.attackAnimation.repeat = 1;
    var atkListener = () => {
      this.arrow();
    };
    this.escena.anims.create(this.attackAnimation);
    this.escena.anims.get("attack")
      .addListener("animationcomplete", atkListener);
  }

  arrow(){
    console.log("arrow");
  }

  attack(){
    if(this.body.onFloor() && this.attackButton.isDown){
      this.setVelocityX(0);
      this.setVelocityY(0);
      this.play("attack", true);
    }
  }

  update() {
    if ( this.body.onFloor() ){
      this.setVelocityY(0);
    }

    this.facing();
    this.idle();
    this.walk();
    this.jump();
    this.attack();

    if (this.body.velocity.y < 0){
      this.play("jump");
    } else if (this.body.velocity.y > 0 && !this.body.onFloor()){
      this.play("falling");
    }

  }
}

What I want to do is:

Player pushes the attack button.
Attack animation plays. I would like it to be played untill it ends, but now I have to keep pushing the attack button.
When attack animation ends, the function "arrow" is executes in order to make an arrow appear.

Thanks in advance.


texts:
I just started learning a few things about libGdx and i don't really understand how the camera works because i've created a camera, then set the camera position to viewport.getWorldWidth()/2 and viewport.getWorldHeight()/2 and then i would like to draw a image at 0,0 or where the camera starts drawing but i don't really understand why it's not working.Here's the code:

public class PlayScreen implements Screen {

    private OrthographicCamera cam;
    private Viewport viewport;
    private MainClass mainClass;
    Texture img;

    public PlayScreen(MainClass mainClass){
        this.mainClass = mainClass;
        img = new Texture(Gdx.files.internal("badlogic.jpg"));
        cam = new OrthographicCamera();
        viewport = new StretchViewport(400, 200, cam) ;
        cam.position.set(viewport.getWorldWidth()/2, viewport.getWorldHeight()/2, 0);

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
            cam.position.x += 100 * delta;
            System.out.println(cam.position.x);
        }

        if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
            cam.position.x -= 100 * delta;
            System.out.println(cam.position.x);
        }

        cam.update();
        mainClass.batch.setProjectionMatrix(cam.combined);

        mainClass.batch.begin();
        mainClass.batch.draw(img, 0  , 0); //here i'm not sure what position should it be
        mainClass.batch.end();
    }

The output it's just a blank window, i don't understand where it starts drawing


texts: How to create a vertex buffer that provides this pattern?

texts: I have a series of vertices that I want to layout with the following configuration, but I haven't been able to find out how to do this with the square and X pattern.  Most of the time I have generally seen a quad split  into two triangles usually using triangle lists.  I suspect this is using triangle strips but I am not exactly sure how to do it.  Could anyone help?


texts:
I'm making a small lockpicking simulator. Obviously I'll need the pick to not pass through the lock, and I'll need the pins to move when you tap or push them with the pick.

Here's what I have so far, just to give you an idea.

http://megaswf.com/serve/2433982

As you can see, the collision detection is pixel perfect. I've looked into a couple of different ways of doing collision response, but it seems like such a vast and complicated field. Any time I come up with a possible solution I start noticing flaws like what would happen if more than two objects collided and so on.

I've looked into physics engines like Box2D, but it seems like such overkill considering the, I think, simple nature of the game I'm trying to make. I don't like the idea of using a huge library that I don't even begin to understand just because I can't figure out how to do collision response.

But I just don't know where to begin. Maybe I will have to use a library. If anyone with experience could, based on that demo and what I'm trying to do, suggest a course of action, I'd really appreciate it.


texts: Accessing an object from another scene in Unity

texts: My game requires the changing of scenes. My game also requires the health to stay the same and not get destroyed in the transition of the scene. Which I did with the use of DontDestroyOnload. In the second scene, I want one of the game object's script to use the health bar(which is in the first scene and using DontDestroyOnload). how do I do that?


texts: Make main game music volume less louder when player getting close to sfx audio object?

texts:
The audio mixer settings :

Then the audio source for the game music :

And the sfx audio source I changed the Spatial Blend to 3D and then in the 3D settings changed the Volume Rolloff to Linear Rolloff Min Distance to 10 and Max Distance to 13.

The sfx effect is working fine but the game music volume stay loud too loud.
How can I make that when the player is getting closer to the fire the main game audio will get less louder not to set the game music volume to 0 but make it slowly also less louder while the sfx getting more louder ?
my problem is to make the game music less louder slowly when the player is getting closer to the fire.


texts: How can I have my game engine track player history?

texts:
I'm in the very early stages of designing a browser-based text RPG. The project is basically just something I'm doing for fun and as a learning experience. I'm starting to wrap my head around the infrastructure of the game and I keep getting hung up on the best way to accomplish this.

If I have a map comprised of a grid with different items/monsters/quests/etc. in each 'tile', what's the best way to keep track of the areas on the grid where the player has been?

If the map is a grid of 1000x1000 squares, I want to know that in the player's entire gaming history, they have already visited squares A-1, F-6, GQ-46, etc. This list could be huge for each and every player.

Along the same lines, if I have quest-dependant events, how do I track the quests players have completed? Each player would need to have something letting the engine know if they have or have not completed potentially hundreds of quests.

My first idea was to save this information somehow in each player entry in the database, but that would mean a field for every one of the tiles in the 1000x1000 map. That doesn't seem like it would scale.

I'm just not sure how to store the info that lets the engine say "hey, I know that out of all the tiles on the map, this player has been on this particular one before." or "out of all the quests, this player has completed this particular one".

What is the best way to approach this?


texts:
I just tried Farseer and everything is working great. My problem is, that on touch the player should get an force up. Although the touch event works well, the player did not get an force!

Here my code:

 public void Update()
    {

        if (acceleration.Y < 0)
        {
            body.Rotation += ConvertUnits.ToSimUnits(0.05f);
        }

        if (acceleration.Y > 0)
        {
            body.Rotation -= ConvertUnits.ToSimUnits(0.05f);
        }

        while (TouchPanel.IsGestureAvailable)
        {
            var gesture = TouchPanel.ReadGesture();
            if (gesture.GestureType == GestureType.Tap || gesture.GestureType == GestureType.Flick)
            {
                Debug.WriteLine("Okey");
                body.ApplyForce(new Vector2(0, -20));
            }
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(playertexture, ConvertUnits.ToDisplayUnits(body.Position),null,Color.White, ConvertUnits.ToDisplayUnits(body.Rotation), new Vector2(playertexture.Width / 2, playertexture.Height / 2), 1f,SpriteEffects.None, 0f);
    }


texts: Cache friendliness of AABB-Tree: binary vs N>2

texts:
I found that state-of-the-art physics engines like Bullet and Box2D all use binary AABB-Tree for broad-phase collision detection.

I wonder, did anybody tested AABB-tree with >2 branches per node ?

I always had feeling that binary trees are extremely cache unfriendly, since you have to dereference pointers (resp. indexes) at each level, and whole your tree does not fit into cache. Since you have log_2(N) levels, I assume you have ~log_2(N) cache misses. Cost of cache miss can be ~100 CPU cycles. With N=4 base tree you would have just half cache misses (log_4(N) = log_2(N)/2), but you would need to do 2x more AABB comparisons at each level (yet you have less levels). Assuming AABB comparison cost less than 100 CPU cycles (especially using SIMD SSE/AVX ops ), using N=4 should be faster.

But I assume balancing N-tree is much more complex than binary tree, which deters people from implementation, and also can add runtime cost.


texts: Open website URL from image marker using ARCore in Unity

texts:
How can I open a website URL from an image marker using ARCore in Unity?
I am trying to build an AR app using ARCore in Unity. I have ten images and ten url links to websites, I need to link the ten images with those ten url links. When I scan the image with the phone's camera, I want the URL to open directly.
I've done image tracking with video before, but now I want to do image tracking linking to a URL.


texts: Can I position a player avatar behind the camera based on rotation?

texts:
I'm currently reverse engineering a video game where what's rendered on the screen depends on the proximity of the player avatar to the camera. As such, for my freecam to work properly, I need to bring the player avatar along with the camera.

Since I can't yet find how the player avatar is rendered to the screen, the next best thing I can think to do is to place the player avatar behind the camera at all times (I suppose essentially like making the player avatar orbit the camera, but always be behind it).

I just can't quite pin down how to make this happen.

The values I have are as follows:

Player Avatar:

X
Y (Up/Down)
Z

Camera:

X
Y (Up/Down)
Z
Pitch (In degrees natively, but converted to radians for my calculations)
Yaw (In degrees natively, but converted to radians for my calculations)

World Orientation:

To get my camera to move forward in the direction I'm pointing my mouse when pressing the Y key, these are the calculations I'm using (code is in Lua):

--//Camera XYZ values
local camCoordX = readFloat("[cameraBase]+990") --Camera X
local camCoordY = readFloat("[cameraBase]+994") --Camera Y
local camCoordZ = readFloat("[cameraBase]+998") --Camera Z

--//Camera pitch and yaw
local pitch = math.rad(readFloat("[cameraBase]+1540")) --Pitch
local yaw = math.rad(readFloat("[cameraBase]+1544")) --Yaw

--//Sine and cosine calculations
local sinOfYaw = math.sin(yaw) --Sine of Yaw
local cosOfYaw = math.cos(yaw) --Cosine of Yaw
local sinOfPitch = math.sin(pitch) --Sine of Pitch
local cosOfPitch = math.cos(pitch) --Cosine of Pitch

--//If Y key is pressed, write new camera XYZ values accordingly
if isKeyPressed(VK_Y) then
    writeFloat("[cameraBase]+990", camCoordX + (sinOfYaw * speed))
    writeFloat("[cameraBase]+994", camCoordY - (sinOfPitch * speed))
    writeFloat("[cameraBase]+998", camCoordZ + (cosOfYaw * speed))
end

Based on that information, is it feasible for me to accomplish placing the player avatar behind the camera at all times based on rotation? I'm open to other suggestions or options as well. Thank you for any help you can offer!


texts: Are closing window and destroying DirectX11.1 independent?

texts:
I have a project with DirectX support.
In this program uses two threads.
One is a dedicated message loop and the second is executing DirectX API's.
The question is about ending such program.
The WM_CLOSE sends asynchronous command, that stops rendering and exits DirectX loop too. After that it destroys the window.
Everything works fine. The question is, is this algorithm OK?
Should the window's thread or the DirectX thread be synchronized (dependent)?


texts: Simple OpenGL program major slow down at high resolution

texts:
I have created a small OpenGL 3.3 (Core) program using freeglut. The whole geometry is two boxes and one plane with some textures. I can move around like in an FPS and that's it. The problem is I face a big slow down of fps when I make my window large (i.e. above 1920x1080). I have monitors GPU usage when in full-screen and it shows GPU load of nearly 100% and Memory Controller load of ~85%. When at 600x600, these numbers are at about 45%, my CPU is also at full load. I use deferred rendering at the moment but even when forward rendering, the slow down was nearly as severe. I can't imagine my GPU is not powerful enough for something this simple when I play many games at 1080p (I have a GeForce GT 120M btw). Below are my shaders,

First Pass

#VS
#version 330 core

uniform mat4 ModelViewMatrix;
uniform mat3 NormalMatrix;
uniform mat4 MVPMatrix;

uniform float scale;

layout(location = 0) in vec3 in_Position;
layout(location = 1) in vec3 in_Normal;
layout(location = 2) in vec2 in_TexCoord;

smooth out vec3 pass_Normal;
smooth out vec3 pass_Position;
smooth out vec2 TexCoord;

void main(void){

    pass_Position = (ModelViewMatrix * vec4(scale * in_Position, 1.0)).xyz;
    pass_Normal = NormalMatrix * in_Normal;
    TexCoord = in_TexCoord;

    gl_Position = MVPMatrix * vec4(scale * in_Position, 1.0);
}

#FS
#version 330 core

uniform sampler2D inSampler;

smooth in vec3 pass_Normal;
smooth in vec3 pass_Position;
smooth in vec2 TexCoord;

layout(location = 0) out vec3 outPosition;
layout(location = 1) out vec3 outDiffuse;
layout(location = 2) out vec3 outNormal;

void main(void){
    outPosition = pass_Position;
    outDiffuse = texture(inSampler, TexCoord).xyz;
    outNormal = pass_Normal;
}

Second Pass

#VS
#version 330 core

uniform float scale;

layout(location = 0) in vec3 in_Position;

void main(void){
    gl_Position = mat4(1.0) * vec4(scale * in_Position, 1.0);
}

#FS
#version 330 core

struct Light{
    vec3 direction;
};

uniform ivec2 ScreenSize;
uniform Light light;

uniform sampler2D PositionMap;
uniform sampler2D ColorMap;
uniform sampler2D NormalMap;

out vec4 out_Color;

vec2 CalcTexCoord(void){
    return gl_FragCoord.xy / ScreenSize;
}

vec4 CalcLight(vec3 position, vec3 normal){

    vec4 DiffuseColor = vec4(0.0);
    vec4 SpecularColor = vec4(0.0);

    vec3 light_Direction = -normalize(light.direction);
    float diffuse = max(0.0, dot(normal, light_Direction));

    if(diffuse > 0.0){
        DiffuseColor = diffuse * vec4(1.0);

        vec3 camera_Direction = normalize(-position);
        vec3 half_vector = normalize(camera_Direction + light_Direction);

        float specular = max(0.0, dot(normal, half_vector));
        float fspecular = pow(specular, 128.0);
        SpecularColor = fspecular * vec4(1.0);
    }
    return DiffuseColor + SpecularColor + vec4(0.1);
}

void main(void){

    vec2 TexCoord = CalcTexCoord();
    vec3 Position = texture(PositionMap, TexCoord).xyz;
    vec3 Color = texture(ColorMap, TexCoord).xyz;
    vec3 Normal = normalize(texture(NormalMap, TexCoord).xyz);

    out_Color = vec4(Color, 1.0) * CalcLight(Position, Normal);
}

Is it normal for the GPU to be used that much under the described circumstances? Is it due to poor performance of freeglut?

I understand that the problem could be specific to my code, but I can't paste the whole code here, if you need more info, please tell me.


texts: Automatically generate low detail collision meshes

texts:
I lately integrated Bullet Physics into my little game engine, but for now I only use basic shapes as spheres or boxes for collision checks. For more realistic physics I need collision meshes for all models in the scene. They should be much simpler and in lower detail than the actual model for drawing to speed up computations.

Since I want adding new asserts to the engine as easy as possible, I am looking for a way to automatically generate collision meshes. I could just use the actual mesh loaded from file and that would result in very realistic physics calculations but that won't be fast enough. Therefore, how can I generate low detail collision meshes from a given set of vertices?

This task doesn't seem trivial since there many different cases to handle. For example a model of a house with furniture must retain details of floor and door frames while ornaments should be removed. I believe there already was research on this topic, but I couldn't find anything useful yet.


texts: storing procedurally generated roguelike world into zones

texts:
I am currently developing a 3D roguelike game which will take place in a very large world. The world is generated by procedural algorithm supplied by external script in run time. To speed up rendering and minimalize memory requirenments I am dividing world into zones. A zone is a 2D rectangle of maximum size 1024 x 1024 (doesn't need to be a square), that holds dynamically allocated (via single new) array of Tile's. Tile is defined to be as small as possible, to minimalize use of memory. Only the zones visible to screen or in immediately neighbor are in memory, rest are loaded from harddisc file on the need to basis.

The problem I have is that map generator does not need to know about logical zone layout, so it can generate this kind of map (especially for higher Z-levels, like lofts in city):

This would be waaaay too much memory waste to enclose it in 1024 x 1024 so, it's better to put it into smaller chuncks like this:

So, finally the question: how can I convert data supplied by world generator script into actual world structure in memory?

What I've thought about so far:

Script has a method SetTile(x, y, tileType), and the world is automatically recalculated every let's say 100 cells, so the zones are put as efficiency as possible. This will require LOTS of zone copying, moving, resizing, etc. - that's a really slow operation, but it will keep world layout in logical order, so for example it would be easier to implement methods like GetTile(x, y) in the script
Script has a method SetTile(x, y, tileType) which temporary just store a Tile into std::vector and after everything is done, the world runs a second pass that's calculates zones. This is way faster, but has a drawback - since Tile are set in no particular order, it's really hard to have GetTile(x, y) method in the script. Perhaps there is a solution for that drawback, I am just not having any idea of - std::map is way too slow to be used here.
If it cannot be done off screen, maybe the solution would be to expose zones into script and being created explicitly (I mean put into script API CreateZone() function and similar) - I don't want this, because scripts will be exposed to end users and I want to make them as robust as possible.
Perhaps there is other solution? Maybe I can organize world generation in some other way (I still need scripts, but it may be a script that generates only part of the world and then connect)?

Additional things I just came up: the entire world can be too large to be put in the memory at once. So it twist the problem even further - I have to break world generation part (in script) into stages. Any suggestions?

As for technology: I am using C++ 03' without Boost and AngelScript as scripting language


texts:
I can't get my head wrapped around this issue. The issue is my latest code is making the camera zoom in and out really quickly.

My approach is built on -

http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-6-implementing-the-pinch-zoom-gesture/1847?tag=content;siu-container

The opengl scale will be getting the variable - scale.

gl.glScalef(scale, scale, 1);

the distance is obtained by between two fingers, old distance (initial touch points), and new distance (dragging touch points). The zooming in and out works well. However, it would reset glScalef each time the user start using pinch zoom.

scale = newDistance / oldDistance;

I tried calculating by additive ratio. The oldtscale handles the previous distance, if it is same, then it doesn't need to add up anything to scale. The zooming is really quick, I moved the fingers closer by mere 1 cm to 5 cm, zoom goes down or up fast.  I think additive ratio is a bad solution. I think it might be incomplete solution. I'm trying to figure out what's wrong with it.

//additive ratio
tscale = (newDistance / oldDistance) - 1;
                    if(oldtscale == tscale) {
                        oldtscale = tscale;
                        tscale = 0;
                    }
                    else {
                        oldtscale = tscale;
                    }
                            //adding up the additive ratio and scale
                    tscale = scale + tscale;
//checking tscale for limiting the maximum/minimum scale
if(tscale >= 2) {
                        tscale = 2;
                    }
                    else if(tscale <= 1) {
                        tscale = 1;
                    }
                    //supply scale
                    scale = tscale;


texts:
Say I build a snooker game, where balls need to jitter around.

Balls belong to a class (ball class), where all the ball functions are defined.

In the animation, time evolves by a clock ticking within a time loop.

I wonder if the clock function/time loop should be optimally defined in the main program or the class file?

If defined in the class, the advantage is that all functions regarding ball movements, collisions etc, which take time to happen, can be put in the class, without worrying about the time loop; the disadvantage is that time will tick for every ball separately, which obviously looks bad.


texts: I have a libGDX project, in which I have a Box2D world, which is currently filled with some boxes as a terrain. I also added a DirectionalLight to the scene for simulating the Sun. I almost have the effect I'd like to achieve, but is there any way to let the light shine through the water more deeply than it does on the surface?


texts: How can I introduce time pressure on the player's decisions?

texts:
I am designing a hacking game, in which the player usually can take his time thinking about how to overcome the obstacles that he/she currently faces. However, I decided that besides coming up with clever solutions, hacking should also feel intense, and that the game needs some ways to put a time pressure on the player's decisions.

First such mechanic that I added reassured me that I am going in the right direction: Sometimes the player can trigger a network trace, which lasts X seconds and can potentially kick the player out of the network unless he/she reacts quickly enough and succeeds in evading the trace. I would like to add perhaps one or two more mechanics that would put the player under a time pressure, but I am a little stuck and always seem to come up with a variations on  'Countdown', i.e. 'There will be (a punishment) in (X) seconds, unless (some action is taken)', but obviously all those mechanics end up too similar.

In abstract terms — that is, without knowing the particular mechanics in my ruleset — how can I introduce a time-pressure on the player's decisions?


texts:
I'm trying to load text from a .txt file into a TextAsset variable. The file is in the assets folder under Texts/. My problem is that bindata is returned as null.

string instructions;

void Start ()
{
    //LOAD TEXT ASSETS

    TextAsset bindata = Resources.Load ("Texts/Instructions") as TextAsset;
    instructions = bindata.text;
}


texts: How can I prepare the different difficulty levels for my game?

texts:
I've though about creating the game for the easiest difficulty level, and from there scale up and create the other, more difficult difficulty levels, but I'm not sure it's the fastest way to go.

How should I create the different difficulty levels for my game?


texts: Destroying a static mesh component in C++

texts:
I am making a maze game with secret walls that I want to be destroyed when a certain score is reached. I currently have a fully working game where I can pick up objects, track my score, and then end the game and take me back to the main menu when all items are picked up. What I want to do is change the game so when a score is reached, the wall disappears and the map can be extended in that direction. However, I can't seem to figure out how to get the wall to be destroyed. I believe I may not be referencing it correctly in C++ code, but can't find a way to do it correctly. Anyone see what I'm doing wrong?

I should also mention that I DO NOT have a C++ file for the BP_SecretController. I tried making one, but couldn't figure out how (Don't remember how I did it with the others because this is an old project and I'm jumping back into UE4 for the first time in months).

FinalGameModeBase.cpp

    if (Score >= 12.0f)
{
    BP_SecretController2->DestroyComponent();
}

FinalGameModeBase.h

UPROPERTY(EditAnywhere, Category = Building)
    UStaticMeshComponent* BP_SecretController2;


texts: In OpenGL what's quicker, lots of smaller VAOs, or one large one updated each frame?

texts:
In my game engine, a mesh can be made of many submeshes. These submeshes may or may not share vertex data with the rest of the mesh, if they don't they have their own vertex data array.

I've noticed that rendering a mesh with many submeshes that don't share vertices is incredibly slow. This is because each submesh has it's own VAO (and vertex/index VBO pair).

The alternative is to gather the vertices and indices into one pair of VBOs and update them every frame. But will this be much faster?

Is it faster to create one large VAO and update it every frame, or to render many small ones which don't need updating each frame?


texts: Finding diagonal objects of an object in 3d space

texts:
Using Unity3d,
I have a array which is having 8 GameObjects in grid and one object (which is already known) is in center like this where K is already known object. All objects are equidistant from their adjacent objects (even with the diagonal objects) which means

(distance between 4 & K) == (distance between K & 3) = (distance between 2 & K)

1 2 3
4 K 5
6 7 8

I want to remove 1,3,6,8 from array (the diagonal objects).
How can I check that at runtime?

my problem is the order of objects {1-8} is not known so I need to check each object's position with K to see if it is a diagonal object or not. so what check should I put with the GameObjects (K and others) to verify if this object is in diagonal position
Regards,
Sam


texts: How to apply saturn's ring texture in Unreal Engine 4?

texts:
I'm working on a "solar system" model project. And while trying to apply saturn's ring texture which is this one :

it ended up looking like this:

I'm new to UE4 and this branch in general. So I have no idea how to fix this .
your help would be appreciated


texts: Keep gravity velocity the same all the time

texts: I have 2D rigidbodies that fall to the ground, however they speed up while falling. Also, when they freeze in the air and then unfreeze, the velocity is set to 0 and they gradually start speeding up again. How can I keep the velocity constant at all times, until they hit the ground?


texts:
I am currently developing a 2,5D Sidescroller in Unity (just starting to get to know it).

Right now I added a turn-script to have my character face the appropriate direction of movement, though something with the movement itself is behaving oddly now.

When I press the right arrow key, the character moves and faces towards the right.
If I press the left arrow key, the character faces towards the left, but "moon-walks" to the right.

I allready had enough trouble getting the turning to work, so what I am trying is to find a simple solution, if possible without too much reworking of the rest of my project. I was thinking of just inverting the movement direction for a specific input-key/facing-direction.

So if anyone knows how to do something like that, I'd be thankful for the help.

If it helps, the following is the current part of my "AnimationChooser" script to handle the turning:

    Quaternion targetf = Quaternion.Euler(0, 270, 0); // Vector3 Direction when facing frontway
    Quaternion targetb = Quaternion.Euler(0, 90, 0); // Vector3 Direction when facing opposite way

    if (Input.GetAxisRaw ("Vertical") < 0.0f) // if input is lower than 0 turn to targetf
    {
        transform.rotation = Quaternion.Lerp(transform.rotation, targetf, Time.deltaTime * smooth);
    }
    if (Input.GetAxisRaw ("Vertical") > 0.0f) // if input is higher than 0 turn to targetb
    {
        transform.rotation = Quaternion.Lerp(transform.rotation, targetb, Time.deltaTime * smooth);
    }

The Values (270 and 90) and Axis are because I had to turn my model itself in the very first place to face towards any of the movement directions.


texts: How are Volumetric Effects made within games? (e.g. Smoke/Fire)

texts:
For computer generated volumetric elements such as clouds, fire, and whitewater.

How are they made? Is it just a simple collection of particles [put to pixels] taken from Physics equations or are the like textures?

How are they applied? I would assume not from UV mapping

Derbis, smoke and fire come from the vehicle.


texts: How do I read color data from UTexture2D in UE4?

texts:
Here's my code:

// get RenderTarget2D
static ConstructorHelpers::FObjectFinder<UTextureRenderTarget2D> TargetObj(TEXT("/Game/Textures/RenderTexture"));
// generate a UTexture2D
CameraTexture = TargetObj.Object->ConstructTexture2D(Target->GetOuter(), "mytexture", Target->GetFlags(), 255);
//Turn off Gamma-correction
CameraTexture->SRGB = 0;

//Guarantee no garbage collection by adding it as a root reference
CameraTexture->AddToRoot();

//Update the texture with new variable values.
CameraTexture->UpdateResource();

GetColor(CameraTexture);

...

FLinearColor ANextGenHUD::GetColor(UTexture2D *MyTexture2D)
{
     FColor* FormatedImageData = static_cast<FColor*>(MyTexture2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_ONLY));
     for (int32 y = 0; y < MyTexture2D->PlatformData->Mips[0].SizeY; y++)
     {
         for (int32 x = 0; x < MyTexture2D->PlatformData->Mips[0].SizeX; x++)
         {
             int32 curPixelIndex = (y * MyTexture2D->PlatformData->Mips[0].SizeX) + x;
             FColor c = FormatedImageData[curPixelIndex];
             c.A = 255;
             MyTexture2D->PlatformData->Mips[0].BulkData.Unlock();
             return c;
         }
     }
}

This code is a bit messy fo testing purposes, but shoiuld theoretically get me the color of the first pixel. Instead it just gives me a random color the constantly changes as well when I draw it on the HUD.

What am I doing wrong?


texts: Shadow Mapping, why does my shadow change size and position when I rotate my light?

texts:
I have looked far and wide for this and have not found any issue like this, so far. Basically, when my light is at a certain angle my shadows seem to be correctly positioned and scaled, yet if I rotate the light about itself, both of these things change.

It should be about that size and position but it is rotated incorrectly here.

In this image, it is completely incorrect.

Now for my code.

1st, the code run on the CPU concerning the shadow map:

In the load, I create my shadow map based on the width and height of the screen.

shadow = shadow_map(renderer::get_screen_width(), renderer::get_screen_height());

And I set up my shaders, no need to show it, that bit's working. In the update method I give my shadow map the properties of the light used to create the shadow like so:

shadow.light_dir = normalize(spot.get_direction());
shadow.light_position = spot.get_position();

Then in my render method I do this:

renderer::set_render_target(shadow);
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
renderer::bind(shadow_eff);
for (auto &e : meshes)
{
        auto m = e.second;
        auto M = m.get_transform().get_transform_matrix();
        auto V = shadow.get_view();
        //glm::lookAt(light_position, light_position + light_dir, glm::vec3(0.0f, 1.0f, 0.0f));
        auto P = cam.get_projection();
        auto MVP = biasMatrix * (P * V * M);
  glUniformMatrix4fv(shadow_eff.get_uniform_location("MVP"),1,GL_FALSE,value_ptr(MVP));
renderer::render(m);
}

glCullFace(GL_BACK);
//set render target back to screen
renderer::set_render_target();

//...

auto lM = m.get_transform().get_transform_matrix();
        auto lV = shadow.get_view();
        auto lP = cam.get_projection();
        auto lMVP = (lP * lV * lM);

        glUniformMatrix4fv(main_eff.get_uniform_location("lightMVP"), 1, GL_FALSE, value_ptr(lMVP));

//bind the shadow map texture
renderer::bind(shadow.buffer->get_depth(), 1);
        glUniform1i(main_eff.get_uniform_location("shadow_map"), 1);

It is worth noting that my bias matrix looks like this:

0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0

Now onto the shader code:

void main()
{
    // **********************
    // Calculate shade factor
    // **********************
    float shade = calculate_shadow(shadow_map, light_space_pos);
    // ************************
    // Calculate view direction
    // ************************
    vec3 view_dir = normalize(eye_pos - position);
    // **************
    // Sample texture
    // **************
    vec4 tex_colour = texture(tex, tex_coord);
    // ********************
    // Calculate spot light
    // ********************
    colour = calculate_spot(spot, mat, position, normal, view_dir, tex_colour);
    // *********************
    // Scale colour by shade
    // *********************
    colour *= vec4(shade, shade, shade, 1.0);

    colour.a = 1.0;
}

Where calculate_shadow(...) looks like this:

float calculate_shadow(in sampler2D shadow_map, in vec4 light_space_pos)
{
    vec3 light_dir = normalize(spot.position - position);

    vec3 proj_coords = light_space_pos.xyz / light_space_pos.w;

    proj_coords = proj_coords * 0.5 + 0.5;

    float closest_depth = texture(shadow_map, proj_coords.xy).r;
    float current_depth = proj_coords.z;

    float bias = max(0.05 * (1.0 - dot(normal, light_dir)), 0.005);

    float shadow = current_depth - bias > closest_depth ? 0.0 : 1.0;
    return shadow;
}

and the most important part of the shadow vertex shader is:

vertex_light = (lightMVP * vec4(vertex_position, 1.0));

I've been thinking about this on and off for weeks, any help is appreciated. In my experience it's usually something small that I've got wrong. Thanks in advance.


texts: Why do we put deltaTime as an argument in render() LibGDX?

texts: I know that deltaTime is the time the last frame took to be rendered. However, I have no idea why we have to put it inside the parameter of the render method. I also don't know how the render method takes use of the deltaTime.


texts:
After cocos2d, I'm looking at box2d... And I have some questions:

I was wondering how to cut a body into pieces.

How do I determine the intersection point of the body with the cut line?
Create a new body in some "update_body_method"?

On the second question I have answer, for example between two points create vector from first point to second point.


texts: Sprite Kit - containsPoint for SKPhysicsBody?

texts:
I have a ball bouncing around the screen. I can pick it up and drag it onto a "bucket".

When my touches finish, I use the containsPoint function to check and see if I have dropped the ball onto the bucket.

This works fine, however, I actually want to check whether the ball is dropped onto the bucket node's physics body because my "bucket" is actually just an oval, and so I've applied a physics body which is the same shape as the oval, so that the white space around the oval isn't included in the physics simulation.

I can't seem to find a "containsPoint" function for physics bodies. Can anyone advise on how I'd check for this?

To summarise, I want to drop a node, onto a specific part of another node (or its physics body) and trigger an event.

Thanks in advance.


texts:
In my AndEngine-based game there are a few sprites on the scene. One sprite acts as a surface and the rest of them are placed on top of this surface. I want to take unique actions whenever any of the these sprites is touched (the surface as well as the sprites on top of it). When I attach use registerTouchListerner for the surface sprite the Touch Listener does not work for any other sprite on top of it. Touching the sprites on top triggers the event, but it thinks that the surface sprite has been touched.

When I remove the touch listener from the surface it can successfully responds to touch event for the rest of the sprites on top.

So, does the AndEngine allow to attach OnAreaTouch listener to sprites on the top layer when the bottom layer sprite has already been attached to a touch listener?

(OnSceneTouched event cannot be used, as the 'surface' sprite only occupies bottom half of the screen and not the complete scene background)


texts: Converting Projected Vertex Positions to Normalized Device Coordinates

texts:
I'm using directx 9 and vertex shaders to rasterize triangles...I have vertex shader input structs like this:

struct VS_INPUT_Quad
{
   float4 Position : POSITION;
   float2 UV : TEXCOORD0;
};

and pixel shader input structs like this:

struct PS_INPUT_Quad
{
   float4 Position : POSITION;
   float4 Pos2 : TEXCOORD0;
   float2 UV : TEXCOORD1;
};

Here is vertex shader:

    PS_INPUT_Quad SkyboxVisibilityPass_Vertex_Shader( VS_INPUT_Quad Input )
    {
        PS_INPUT_Quad Output = ( PS_INPUT_Quad )0;

// projected vertex position
        Output.Position = mul( Input.Position, mWVP );

// normalized device coordinates of the vertex
        Output.Pos2 = Output.Position / Output.Position.w;
        Output.Pos2.xy *= float2( 0.5, -0.5 );
        Output.Pos2.xy += float2( 0.5, 0.5 );

// prop uv coordinates
        Output.UV = Input.UV;

        return( Output );
    }

Here is pixel shader( simply returns a color from a texture ):

    float4 SkyboxVisibilityPass_Pixel_Shader( PS_INPUT_Quad Input ) : COLOR0
    {
        return tex2D( g_SamplerMultiplier, Input.Pos2.xy );
    }

I'm finding that the Pos2 value sent to the pixel shader is incorrect. Am I incorrectly converting projected vertex position coordinates to normalized device coordinates? PIX says that values are well above 1 when dubugging the pixel shader, however, the output looks correct when looking at the 'mesh' tab while hiliting the draw call...

Here is debug output for a single pixel whose position lies within the clip space:

   //
// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
//
// Parameters:
//
//   sampler2D g_SamplerMultiplier;
//
//
// Registers:
//
//   Name                Reg   Size
//   ------------------- ----- ----
//   g_SamplerMultiplier s0       1
//

    ps_2_0
    dcl t0.xy  // Input<4,5>
    dcl_2d s0
    texld r0, t0, s0  // ::SkyboxVisibilityPass_Pixel_Shader<0,1,2,3>
    mov oC0, r0  // ::SkyboxVisibilityPass_Pixel_Shader<0,1,2,3>

// approximately 2 instruction slots used (1 texture, 1 arithmetic)

Registers:
    oC0 (0.435, 0.435, 0.435, 1.000)    float4
r0  (0.435, 0.435, 0.435, 1.000)    float4
s0      float4
t0  (11.871, 8.631, 0.000, 0.000)   float4

As you can see above, t0 is the Pos2 coordinates that i use to sample the texture...they are well above 1 ... the vertex they belong to is visible so this pixel should have valid normalized device coordinates. Are the coordinates being altered after leaving the vertex shader and arriving at the pixel shader?