texts: How do I build interesting mechanics-driven puzzles for my stealth game?

texts:
I'm currently working on a turn-by-turn puzzle stealth game (as a student group project), inspired by Tiny Heist. The basic mechanic is that every time the player moves a square / does a thing, every NPC moves as well.

My objective is to make an experience similar to Portal: the player goes from room to room, each room has an entrance and an exit, with obstacles between them. The player can see where the exit is, as well as the obstacles, and must leverage the game mechanics to bypass the obstacles and reach the exit.

An example room would be:

There is a corridor, with a guard going back and forth. The exit is at the end of the corridor.
There is a closet in the middle of the corridor.
The player must exploit the guard's patrol to hide in the closet, let the guard pass him by, get out of the closet and reach the exit.

I want the player to feel perplexed when they're trying to solve the puzzle; ideally, I want them to feel there is a solution just within their grasp, but they can't find it; and I want them to feel smart once they do solve the puzzle.

The problem is, I don't know how to design puzzles to give that experience. I have a few ideas, some of which feel like they'd make fun "early game" levels, but after a while all the levels I'm sketching feel same-y and boring, or too complicated with too many moving parts (I had the same problem back when I tried to design Portal 2 levels).

I want to create dependencies, levels where the mechanics overlap with one another to make the player think "I need to do X, but I can't do X before I've got Y, but how do I do Y without having done X?". I could add additional mechanics like dogs, or security cameras, but I don't know how to exploit them.

When I try to design a level, the kind of ideas I come up with follow a pattern of "you need to turn off the cameras to progress, but you need to give a bone to the dog to reach the camera, but you need to distract the guard to acquire the dog". These ideas are convoluted, but shallow; they don't feel like they'd make for intellectually stimulating (or even difficult) levels.

What methodology or design pattern can I apply to create richer problem-solving opportunities for the player in this stealth game context, or in any kind of puzzle game?


texts: Games with rubbing/scratching as interaction?

texts:
I'm brainstorming a game aimed for touchscreen. Its primary interaction involves a lot of rubbing and scratching with the finger to the on screen objects, sort of like Fruit Ninja, but a bit more work than a single swipe. I recall there are somewhat similar operation in Rayman Raving Rabbid that uses Wiimote to draw shapes.

At this stage, the interactions in my mind looks repetitive and unappealing. I'm trying to find similar examples that appear repetitive but still fun to play. Besides these two, are there any others?


texts: Multiple semi-dynamic objects in one VBO

texts:
I am working on a game that uses opengl 3. The huge geometry is spread over a grid of about 270,000 cells. The geometry in each cell, though not very frequently, can change independently from other cells. Usually most of these cells don't contain any geometry at all.

Until now my approach was to have one vertex buffer object per cell.
Today i discovered that alone generating all these VBOs (without any data in them) results in almost 1GB of main memory usage. That would be equivalent to an overhead of around 3KB per VBO.

As it seems this overhead can not be avoided, i first thought of generating a VBO only when the cell creates its first geometry and deleting it once the cell becomes empty again.
This might work quite well, but it would still be inefficient if the geometry happens to have very few geometry in every cell.

So i searched for a different solution and read, that one approach is to put multiple meshes in a single VBO. The problem with that is, that the mesh of a cell may change its size and require more memory in the VBO than initially. This would require subsequent meshes in the VBO to be shifted.

Now my question is: How do i do that?

Do i have to save the mesh for every cell, so i can rewrite it into the VBO when it needs to be shifted?
Would glMapBuffer help me?
Also: Is there a better, completely different solution?

Thanks in advance!


texts: How do I sync client and server when sending player speed changes?

texts:
I'm implementing client-side prediction. Most explanations assume the client sends messages like "Move my player up by 1 position". What if I send messages like "Set my player's velocity to x"?

On the client, the player sets his own velocity (by client-side prediction) before the server does, resulting in the two getting out of sync. This problem persists even considering average latency.

How can I tackle this?


texts: Unity 3D - Rotating an object in relation to its velocity

texts:
I am currently trying out Unity 3D and I've run into a problem. The problem is I have a car that moves along a road and then when it reaches a corner I would like it to turn the corner and have the model rotate based on its current velocity.

Here is the code I have for moving the object forward:

_velocity += (_velocity * Time.deltaTime) + (_acceleration / 2f) * Time.deltaTime * 2f;
_velocity = Mathf.Clamp(_velocity, 0f, MaxVelocity);
Vector3 position = this.transform.position;
position += -this.transform.forward * _velocity * Time.deltaTime;
this.transform.position = position;

The variables are declared as class members:

private const float MaxVelocity = 10;
private float _velocity;
private float _acceleration;

This appears to work OK for moving forward. If I applied a rotation it may look OK for a certain velocity, but if the velocity changes, then the rotation seems to quick or to slow.

What I would like (but completely failing at accomplish) is when it comes time to turn, then I would look at the velocity and calculate a smooth rotation so when an object performs a turn it will always end up at the same point regardless of how quick it approaches the corner.

I have tried a number of options, over countless hours, but I'm not having any luck!

Any ideas?

UPDATE #1:

Below is a half-way solution I got, but for now I will add it here and leave the question open for a bit in case someone can provide a better approach.

From what I worked out a LERP rotation from the current direction to the new direction did the trick (kind of!). So, I created a behaviour called VehicleController and in the Awake method I added this:

_target = this.transform.rotation * Quaternion.Euler(0f, 90f, 0f);

This gave me the target rotation relative to my current rotation, i.e. my rotation would have to equal _target for me to be facing in the desired direction. I then added the following to the FixedUpdate method:

//  Rotate
if(_doTurn)
{
    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, _target, Time.fixedDeltaTime * _velocity);
}

This performed the actual rotation. The key part was setting the third parameter Time.fixedDeltaTime * _velocity. This meant that my rotation speed matched my velocity.

My final FixedUpdate method looked like this:

//  Forward
_velocity += (_velocity * Time.deltaTime) + (_acceleration / 2f) * Time.fixedDeltaTime * 2f;
_velocity = Mathf.Clamp(_velocity, 0f, MaxVelocity);
Vector3 position = this.transform.position;
position += -this.transform.forward * _velocity * Time.fixedDeltaTime;
this.transform.position = position;

//  Rotate
if(_doTurn)
{
    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, _target, Time.fixedDeltaTime * _velocity);
}

In this sample I had a BoxCollider that triggered the turn, so in the OnTriggerEnter method I simply set _doTurn to true.

Now there are a few things with this:

After the turn I had to fix the positioning and rotation a little. The values were off by about .2, but I couldn't really notice any oddness to care.
This approach gives a quick snap change in direction which wasn't what I was really after. Ideally I wanted a situation where the turn would be gradual at a certain angle and end in the same point. But, to be honest, it looks OK and that gets me moving on for now! :)

With regards to #1 I think I had to fix some of the position/rotation values because I was using a BoxCollider to trigger the turn so there may be better approaches.


texts: Whenever I grapple onto a RigidBody, the grappling/reeling mechanics glitch out in Unity. How can I fix this?

texts:
I'm trying to make a game in Unity 2020.1, the feature I'm trying to prototype and test is a grapple gun. The grapple gun should grapple onto walls, and platforms reel the player in. I've implemented this already using the below code:
if (Input.GetMouseButton(0))
       {
            RaycastHit2D hit = Physics2D.Raycast(crosshair.transform.position, mousePos - (Vector2) crosshair.transform.position);

            hitPoint = hit.point;

            if (hit.collider != null)
            {
                if (!isStrung)
                {
                    if (hit.collider.gameObject.CompareTag("Ground"))
                    {
                        Debug.DrawLine(crosshair.transform.position, hitPoint, Color.red, 5);
                        Debug.Log(hitPoint);
                        isStrung = true;
                        distance = Vector2.Distance(transform.position, hitPoint);

                        springJoint.enabled = true;
                        springJoint.distance = distance;
                        springJoint.connectedAnchor = hitPoint;

                        lineRenderer.enabled = true;
                        lineRenderer.SetPosition(0, transform.position);
                        lineRenderer.SetPosition(1, hitPoint);
                    }
                }
            }
       }

This code handles the raycasting and grappling while this code:
private void FixedUpdate()
    {
        playerRb.AddForce(Vector2.right * xInput * speed);
        if (isStrung)
        {
            if (springJoint.distance > 2)
            {
                springJoint.distance -= 0.1f;
            }
        }

        if (hitObject)
        {
            hitRb.AddForce(((Vector2)transform.position - hitPoint) * objectPull);
        }

    }

handles the reeling.
The problem came in once I added some code to allow the player to grab onto an object with a rigid body, as I wanted to allow the grappling gun to move the object.
An example of the goal I'm working towards in in this gameIQ Ball. I want the line to remain straight, but I also want the reeling effect exhibited in the game above.
Here is the problem-causing code:
else if (hit.collider.gameObject.CompareTag("Object"))
                    {
                        Debug.DrawLine(crosshair.transform.position, hitPoint, Color.green, 5);
                        Debug.Log(hitPoint);
                        distance = Vector2.Distance(transform.position, hitPoint);

                        springJoint.enabled = true;
                        springJoint.distance = distance;

                        lineRenderer.enabled = true;
                        lineRenderer.SetPosition(0, transform.position);
                        lineRenderer.SetPosition(1, hitPoint);

                        hitRb = hit.collider.gameObject.GetComponent<Rigidbody2D>();

                        springJoint.connectedBody = hitRb;

                        hitObject = true;
                    }

[In FixedUpdate()]
if (hitObject)
        {
            hitRb.AddForce(((Vector2)transform.position - hitPoint) * objectPull);
        }

Here's a screen recording which should illustrate the problem:
Google Drive - Screen Rec
When I run the game, the grapple gun works fine while I reel onto a wall, with the tag. "walls", but once I grapple onto the RigidBody (the square), the grapple. gun stops working properly. Sometimes, when I grapple onto the RigidBody, there is a green line (same as the one used to show the ray trace), however, I am unsure as to whether this is actually causing the problem.
My full code is in this HasteBin link: Hastebin


texts:
I am building a 2D game and I want to fire a bullet from my player whenever the player press certain button. But, When I use instantiate and add force to my rigidbody it won't work.
The code is: -

    public bool hit;
    public Rigidbody2D gun;
    public float count;
    public Transform pos;
    public Collision2D col;
    // Use this for initialization
    void Start () {
        hit = false;
    }

    // Update is called once per frame
    void OnCollisionEnter2D(Collision2D col) {
        if (col.gameObject.tag == "firePotion") {
            hit = true;
        }
    }
    void Update () {
        if (hit = true && Input.GetButtonDown ("Fire1")) {
            Rigidbody2D gunPrefab;
            gunPrefab = Instantiate (gun, transform.position, transform.rotation) as Rigidbody2D;
            gunPrefab.AddForce (-pos.forward * 5000);
        }
        OnCollisionEnter2D (col);
    }
}

Here, I am trying to make the player able to shoot whenever he takes a potion. But, Neither the onCollision2D is working nor the AddForce. Why?


texts: UE4.23 - Cast of child of GameUserSettings fails

texts:
I've derived GameUserSettings to add a bunch of custom properties to it. I tried making accessible in blueprint by creating a static method that returns the current GameUserSettings cast to my Child Class.

 Custom_Settings * Custom_Settings::GetCustom_Settings() {
     return Cast<Custom_Settings>(GEngine->GameUserSettings);
 }

Unforunately, the cast fails and returns null, which leads to UE complaining about trying to access none in blueprint (naturally). There was a similar question here, but that led me nowhere, since I've already set DefaultEngine.ini to use my custom settings

 [/Script/Engine.Engine]
 GameUserSettingsClassName=/Script/MyGame.Custom_Settings

I've checked whether GEngine can fetch the Settings, and it appears it can. Does anybody have an idea why the cast might be failing?


texts: Making a 2D gun spin from recoil when it shoots

texts:
I am trying to clone the game "Flip the Gun" as an exercise.
Here is the behaviour I have so far.
And here is the code I am using:
if (Input.GetKeyDown(KeyCode.Space))
{
    rigidbody2D.AddForceAtPosition(
                transform.position-recoilPoint.transform.position * recoilForce,
                recoilPoint.position,
                ForceMode2D.Impulse
    );
}

As you can see in the video, the gun is moving too fast and rotating too fast. It seems out of control. I am not sure if the way of adding force to the gun is correct or not.
Thank DMGregory for editing the question for me. I am new to this family so that helped a lot. :)


texts: How can I handle sprite sheets with nonuniform sprite dimensions?

texts:
For a spritesheet with non-uniform sprite dimensions, how can I get the bounding-rectangles for each individual sprite (i.e. the blue boxes in the following image / I only drew a few examples)?

What I would like to determine are: offset_x, offset_y, width, height

So far, I have only used spritesheets on which all sprites have identical dimensions. In that case, one simply needs to specify the x- and y-offset to get a particular sprite. However, for spritesheets of non-uniform dimensions this doesn't work.

EDIT: Having read through the comments and answers, I rephrased my question to make it more inclusive wrt. the actual process of using a spritesheet in a game. Previously, the question contained the points why people produce spritesheets of non-uniform dimensions and how I can deal with that.


texts: Dealing with multiple 2d sprite animations for the same object

texts:
I am using libGDX for a 2d game. Some of my in-game objects have animations, for example a soldier in top-down view that has a walking animation. That is working fine.

Now, while walking, this soldier could do other things as well, for example firing his gun. So both, walking and firing, can happen at the same time.

My question now is: How does one usually deal with these multiple simultaneous animations for the same object? Do I need different animations (one for just walking, one for just shooting, and one animation for both at the same time), or do I rather split the object into several sprites (eg. the soldier's body separated from his arm with the gun), to animate these parts separately? Or is there even another way to achive this?


texts: How do I design my RPG-like class system in a more modular way?

texts:
I'm building a mod for Terraria that will add classes and their corresponding abilities to the game. You're a warrior? Push your ability key and you'll use your berserk ability.

I'm trying to make my player code as simple as possible. I'd like to set the player's in-game "class" by doing something like this at the top of the player class so the rest of the methods in it can access it later:

//Set class
WarriorClass playerClass == new WarriorClass(playerReference, level)

Herein lies the first issue. I get an error at playerReference that says:

Error   CS0236  A field initializer cannot reference the non-static field, method, or property 'ModPlayer.playerReference'  MyMod

Ok, so I looked that up and set the initialization in the WarriorClass instead:

public Player playerReference = new Player();

And I have this now in my player code:

//Set class
     WarriorClass playerClass = new WarriorClass(level);

Here's the beauty of it. In the gamepad input method within my player code all I ever have to do is:

    //On key presses
    public override void ProcessTriggers(TriggersSet triggersSet)
    {
        if (MyMod.ability1Key.JustPressed)
        {
             playerClass.UseAbility(MyMod.ability1Key);
        }

Now that the ability1 key was pressed, let the WarriorClass handle what to do:

    public void UseAbility(ModHotKey key)
    {
            //Ability 1
            if (key.JustPressed == MyMod.ability1Key)
            {
                //Start berserking
                if (player.HasBuff(ModContent.BuffType<BerserkBuff>()) == false )
                {
                    //Lose 10% of your life
                    lifeLost = player.statLifeMax2 / 10;
                    player.statLife = player.statLife - (int)lifeLost;

                    //Berserk and add damage over in the Buff code
                    player.AddBuff(ModContent.BuffType<BerserkBuff>(), 600, false);
                }

This is all great!!! I can add any amount of classes I want and this player code never changes. Except If I want to add if/then logic to select a class in say, Update() then it breaks the following reference in my gamepad input code:

playerClass.UseAbility(MyMod.ability1Key);

Of course it won't have a reference unless I hard code it at the top of the player file, but I don't know what class a player will be until they pick one.

Am I doing this fundamentally in a bad way or am I missing something else in terms of OO programming? I don't want to have to initialize every class for the character at the top of the file like this:

WarriorClass warriorClass = new WarriorClass(level);
ArcherClass archerClass = new ArcherClass(level);
...

... just to do this in the gamepad input method:

if (classChoice == "Warrior")
{
     warriorClass.UseAbility(MyMod.ability1Key);
}
else if (classChoice == "Archer")
{
     archerClass.UseAbility(MyMod.ability1Key);
}


texts: How expensive is Wwise's SetRTPCValue method?

texts:
In an ideal world I would have an RTPC value that I could set every frame (as it is time-based and needs to count milliseconds).  Is this an expensive call or should I not sweat it?

AKRESULT AK::SoundEngine::SetRTPCValue(
    const char *    in_pszRtpcName,                                 // Name of the RTPC
    AkRtpcValue     in_value,                                       // Value to set.
    AkGameObjectID  in_gameObjectID = AK_INVALID_GAME_OBJECT        // Associated game object ID

);

https://www.audiokinetic.com/library/2015.1.4_5497/?source=SDK&id=soundengine__rtpc.html

Since it may make a difference, I'm using this via a plugin for Unity3D.


texts:
Hi i'm working on my First 2D Game with XNA and I have a little problem.
To give a running effect to my Sprite, I scroll through a SpriteSheet with this code(running right):

if (AnimationDelay == 6)
{
    if (CurrentFrameR.X < SheetSizeR.X)
    {
        ++CurrentFrameR.X;
    }
    else
    {
        CurrentFrameR.Y++;
        CurrentFrameR.X = 1;
    }

    if (CurrentFrameR.Y >= SheetSizeR.Y)
    {
        CurrentFrameR.X = 0;
        CurrentFrameR.Y = 0;
    }

    AnimationDelay = 0;
}
else
{
    AnimationDelay += 1;
}

xPosition += xDeplacement;

And these are the objects used :

Point FrameSizeR = new Point(29, 33);
Point SheetSizeR = new Point(5, 1);
Point CurrentFrameR = new Point(0, 0);
int AnimationDelay = 0;

I have the same Code with different SpriteSheet when the sprite is running Left.
Everything is working fine I'd say 90% of the time but the other 10% the sprite animation stays on one Frame of the SpriteSheet, on both directions(left and right) and it stays stuck until I close the program.
The thing is I can't quite figure out why since it never happens at the same moment..Sometimes after 10,15,30 seconds and sometimes even on boot!
Any idea why?
Thanks in advance and let me know if you need any other parts of the code


texts: How do I create tileable solid noise for map generation?

texts:
Hey guys, I'm trying to figure out how to generate tileable fractals in code (for game maps, but that's irrelevant)
I've been trying to modify the Solid Noise plug-in shipped with GIMP (with my extremely limited understanding of how the code works)  but I cant get mine to work correctly.

My modified code so far (Java)

GIMP's solid noise module that I'm basing my code off of (C)

Here is what I'm trying to achieve but
This is what I'm getting

So if anybody can see what I've done wrong, or has a suggestion how I could go about doing it differently, I'd greatly appreciate it. Thanks in advance.
And if I'm asking way to much or if just a huge failure at life, I apologize.


texts: Does ContentManager.Load() re-read an asset if I have loaded it before?

texts:
Or is it smart enough to know I have asked for it before and return an in memory copy created from the first call?

For example if I have a projectile's texture:

Texture2D projectile;

If then I call:

projectile = ContentManager.Load<Texture2D>("bullet");

every time I want fire a new projectile - am I mallocing this on the heap or am I referencing the same copy in memory? If I am mallocing new memory each time I could keep it in memory myself by making the Texture2D variable static and not calling new each time one is fired! (I was just wondering about the ConentManger). The documentation (as with all the XNA documentation is skint on details: http://msdn.microsoft.com/en-us/library/bb197848.aspx).


texts:
I'm trying to implement a simple OBB vs. OBB collision detection! I don't need to know where the collision occures, I only want to know whether a collision occures.

The problem is, that after lot of research in the internet I only found comments like "It's very simple, just use SAT in 3D" or some complex math. No examples anywhere!

In the best case, the algorithm should use the max/min Vectors of the boxes.

I know, that similar questions where asked before, but (I think) none of them had examples.

Apologise my bad english, I'm German and still in school! Also a reason why I want simple mathes. I hope you can help me and maybe supply me with some code.


texts: Libgdx and Box2D TiledMap render is not smooth

texts:
I'm building simple side scroller game. My player (square) move fast and it interacts with other world objects. Problem is when my player is moving it seems that all world is rendering somehow strange (for example box2d objects are not rendering smooth). When player is not moving everything is ok. Here pic when player is moving

and here when my player stands still

Here I add my code

private OrthogonalTiledMapRenderer renderer;

mapLoader = new TmxMapLoader();
    map = mapLoader.load("level1.tmx");
    renderer = new OrthogonalTiledMapRenderer(map, DIV);
    gamecam.position.set((gamePort.getWorldWidth() / 2),    (gamePort.getWorldHeight() / 2), 0);

public void update(float dt){
        world.step(1/60f, 6, 2);
        if(playerAndGroundTest){
            player.update(dt);
        }

        float x = gamecam.position.x - gamecam.viewportWidth * gamecam.zoom / DIV;
        float y = gamecam.position.y - gamecam.viewportHeight * gamecam.zoom / DIV;

        float width = gamecam.viewportWidth * gamecam.zoom * 2 / DIV;
        float height = gamecam.viewportHeight * gamecam.zoom * 2 / DIV;
        renderer.setView(gamecam.combined, x, y, width, height);

        gamecam.position.set(new Vector2(player.getBody().getPosition().x, (gamePort.getWorldHeight() / 2)), 0);
        gamecam.update();
    }

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

        renderer.render();

        b2dr.render(world, gamecam.combined);
    }

here's Player update function

public void update(float dt){
        body.setLinearVelocity(200 * dt, body.getLinearVelocity().y);
    }


texts: Materials overridden when importing package between 2 machines

texts:
My professor and I are working on unity projects.
He sets up basic scene then gives it to me, and I do detailed adjustment.
The problem is for example: I tweak parameters of some materials, and whenever I export a package for him, he imports the package
...but the old material on his PC overrides the new material I adjusted on my PC.
How can we address this issue?


texts: I'm using LWJGL and OpenGL 1.1 at this time and I was wondering what command is used to change the yaw, pitch and roll?


texts: How can I detect continuous touches/pressed with Unity 4.6's UI elements?

texts:
I've recently switched to Unity 4.6. My previous workflow when creating continuous-input controls (the kind where you measure continuous touch input on a single button) was to create a GUITexture and then perform hit-testing on that texture as long as a finger was touching the screen.

With the new GUI there seems to be no way to measure this type of input, as GUITextures objects can no longer be created and the new UI types don't support hit testing.

I'm talking about a button that's supposed to act like a car accelerator where, for example, a simple OnClick() doesn't work because I need to measure if the button is being pressed continuously rather than it working as an on/off toggle. How can I implement this?


texts: Clearing just the object, not the whole canvas, leaving an uwanted trail

texts:
I'm working on a platform game via poo.

I heard is more efficient to clear just the object you're drawing instead of clearing the whole canvas. So I'm working on this, and all goes well when the player's velocity player.Xvel has an integer value.

But when I use a floating point value for the velocity, then my object leaves a banded trail behind it, like a barcode of stripes and gaps.

Can you help me identify what's causing this artifact?

var canvas = {};
canvas.obj = document.getElementById('canvas');
canvas.ctx = canvas.obj.getContext('2d');
canvas.width = canvas.obj.width;
canvas.height = canvas.obj.height;

var Object = function() {
  this.draw = function() {
    switch (this.fill) {
      case true:
        canvas.ctx.fillStyle = this.color;
        canvas.ctx.fillRect(this.x, this.y, this.width, this.height);
        break;
      case false:
        canvas.ctx.strokeStyle = this.color;
        canvas.ctx.strokeRect(this.x, this.y, this.width, this.height);
        break;
      default:
        console.log('draw err');
    }
  };
  this.clear = function() {

    var prevCoords = {};
    prevCoords.x = this.x - this.xVel;
    prevCoords.y = this.y - this.yVel;
    // lineWidth:fix
    canvas.ctx.clearRect(prevCoords.x, prevCoords.y, this.width, this.height);
  };
};

var player = new Object();
var game = {};

player.width = 10;
player.height = 50;
player.x = 200;
player.y = 150;
player.xVel = 0.9; // try to change this to integer/float value then run
player.yVel = 0;
player.color = 'white';
player.fill = true;
player.movement = function() {
  this.x += this.xVel;
  this.y += this.yVel;
};

game.key = [];
game.fps = 15;
game.obj = setInterval(function() {
  player.clear();
  player.draw();
  player.movement();

}, 1000 / game.fps);
body {
  background: rgb(110, 110, 110);
  color: rgb(230, 230, 230);
}

canvas {
  background: rgb(60, 60, 60);
}
<canvas id="canvas" width="460" height="360"></canvas>
<form action="">
  <label>Game:</label>
  <input type="button" value="run" onclick="" />
  <input type="button" value="stop" onclick="clearInterval(game.obj);console.log('end');" />
</form>


texts:
I have a code with several elements. One of these elements I would like you to initiate hidden.

So I did, set for the progress bar to start hidden. It started to go wrong when and I was calling its visibility (bind) the same stopped starting hidden.

I did a test with this problematic progress bar and another one created on time:

The progress bar that has the visibility setting function appears even if I set it to start hidden:

As I said, I believe that this strange behavior is due solely and exclusively to the fact that there is such a function:

Even though I have created a boolean variable that imposes a condition, the bar insists on appearing:

The variable quoted initiates by default as false:

I thought the blame could be on the return knot, but as you can see in the fourth image, even putting "hidden", the progress bar appears anyway.


texts: Reference sf::RenderWindow from another source file in SFML

texts:
In SFML, How would you be able to reference a window in your main.cpp file to another source file? I want to be able to reference the window made in main.cpp from player.cpp, so I can keep everything organized and not have so much stuff in main.cpp. Any help is greatly appreciated.

Main.cpp

#include "SFML/Graphics.hpp"
#include <iostream>
#include "Player.h"

int main()
{
    sf::RenderWindow window;
    sf::VideoMode vmode(800, 600, 32);
    window.create(vmode, "Test");

    PlayerTest(2);

    //Game Loop
    while (window.isOpen())
    {
        // REMEMBER TO FIX PLAYER.CPP

        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(text);
        window.display();
    }

    return 0;
}

Player.h

#ifndef PLAYER_H
#define PLAYER_H

#include <SFML/Graphics.hpp>
#include <iostream>

void PlayerTest(float speed);

#endif

Player.cpp

#include "SFML/Graphics.hpp"
#include <iostream>
#include "Player.h"

void PlayerTest(float speed) {

    sf::RectangleShape square(sf::Vector2f(100, 100));
    square.setFillColor(sf::Color::Cyan);

    //window from Main.cpp I need to reference
    while (window.isOpen())
    {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
            square.move(0, -speed);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
            square.move(0, speed);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
            square.move(-speed, 0);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
            square.move(speed, 0);
        }

        //Window from Main.cpp I need to reference
        window.clear();
        window.draw(square);
        window.display();
    }
}


texts: Unable to rotate a 2D object, wanting to move it like a ball/wheel

texts:
I'm using Unity2D.

I have a very basic 2D space with a platform, a ball and 2D physics.

Physics is being applied and ball sits on top of the platform.

However, it will not spin.

Below is the script attached to the ball:

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

public class Circle : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;
    private float speed = 10f;
    public Rigidbody rb;

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

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rb.maxAngularVelocity = 999;
        rb.AddTorque(movement * speed);
    }

    void OnMouseDown()
    {
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }
}

The script is attached to the ball, I know this because I'm able to drag it (see OnMouseDown).

I have also tried with other objects such as a rounded-corner square, but I just can't get any spin or torque to be applied.

Below is a screenshot of the inspector on the element.  Circle.cs (the script) is the above pasted script.

Any help appreciated.


texts: Data structure to store breakable parts of a mesh

texts:
I have a wall mesh that is divided into destructible pieces. As it gets destroyed, the wall can collapse into separate objects with physics that can be destroyed as well. (Cut the wall in half horizontally and the top wall becomes a separate object with its own physics).

I already have the adjacency info to know neighbors, but how should I store the pieces so that I can detect when to split them into separate objects?  What kind of tree would suit this and know when the branch was severed and what pieces to make a new object out of?

A test would be to smash a circle out of the wall, and the middle of the circle would fall out and contain only those remaining connected pieces as a new object.

Any examples out there?

Thanks!


texts: need to create formulas for stat, level progression etc. What tools will help the not-mathematically-literate?

texts:
I want to create some of the fundamental guideline formulas for a game I am working on. I am following on from sirlin's advice in that I am starting with some assumptions and working back from there.

So let's say that I want to have the player do an average of 1000hp damage at level 100 and 10 at level one. Is there a tool that I could use to draw this (a low exponential curve) and it would spit out a formula based on the curve?

There are some similar questions on here but none that I can find with any advice on the specifics of making the formulas for these progress curves.

thanks


texts: Compare new Vector2 position with previous Vector2 position

texts:
I'm trying to place different objects in the game area like a grid, but I have some problem with my method that creates this objects and there positions. I'm trying to store  each new positions in a List and then compare each new positions with the ones in the List before it's OK to use it as a new position in the grid of the game area. I only want to use each random position once. Help is preciated! Thanks!

Perhaps ther is a better way to do this?

    public void AddItemsToGameArea(ContentManager content)
    {
        foreach (string buildingPart in contentHouseOne)
        {
            Vector2 newPosition = NewRandomPosition;
            if (!checkPreviousPositions)
            {
                listHouseParts.Add(new HousePart(content, buildingPart, newPosition));
                listUsedPosition.Add(newPosition);
                checkPreviousPositions = true;
            }
            else
            {
                for (int i = 0; i < listUsedPosition.Count(); i++)
                {
                    // Check??
                }

            }
        }
    }

    public Vector2 NewRandomPosition
    {
        get
        {
            return new Vector2(gridPixels * Game1.random.Next(1, 8), gridPixels * Game1.random.Next(1, 8));
        }
    }


texts: Efficient container(s) for units in an 2D RTS game

texts:
As the title says, I'm toying around with developing a 2D space RTS game. All of my units are spaceships that basically just shoot at one another, but they have to do a variety of other things as well: they have to "discover" (notify, draw, etc) other ships and planets not owned by the owner of this ship and within the arbitrary range of the ship's "scanners" (since they would otherwise be hidden), and if the ship is told to fire on an enemy ship, it needs to find the closest enemy (and fly to it if out of shooting range), and then shoot it obviously.

I've been wondering what efficient data containers could I use for the ships if there is going to be a large number of ships (100s to maybe 1000s) and why them? Also to note, is that ships must be distinguished by their owner (I may go to war with one player, so I obviously do not want my ships to search for ships of other players), where ownership will probably be represented by some integer (1 = player 1, 2 = player 2, etc) or maybe the unique pointer/memory address of a "player" object (0x4ff = player 1, 0x5ea = player 2, etc) or some other simple identifier.

I initially thought about using an array of vectors (C++), with the index of the array representing the player and each vector being the ships belonging to that player; then take all ships belonging to whatever player you are at war with and place them into a priority queue, whose root would be the enemy ship closest to a specific (friendly) ship and decide if its in range or not, but this seemed far too slow and memory-expensive, and didn't really address how to scan for ships/planets.

I then read up a few related posts about quadtrees and this lead me to other such tree data structures, like R-trees, that are also used for optimal spatial queries, but I do not quite understand exactly how they work and whether or not they would be best for me, so here we are.


texts: Move enemy left in sin wave motion over time

texts:
I'm trying to create a top down shooting game where the enemy moves in sinusoidal motion over time. For the first 10 seconds the enemy needs to move only left and after that it needs to move left in sin wave motion. This is the code I'm using. `

public float enemySpeed;
float frequency = 5.0f;
float magnitude = 1.8f;

void FixedUpdate()
{
    if(Time.time < 10.0f)
    {
        transform.Translate((enemySpeed* Vector2.left) * Time.deltaTime);
    }
    if(Time.time >= 10.0f)
    {
        transform.Translate(enemySpeed* -1.0f * Time.deltaTime, 1.0f * Mathf.Sin(Time.time * frequency) * magnitude * Time.deltaTime, 0);
    }`

What's happening is that for the first 10 seconds the enemy just moves left but after that all the enemies in the screen start moving in sin wave motion. What I want to achieve is that if the enemy has already spawned before the 10th second, it should move left without sin motion. Right now if the enemy is in the middle of the screen and the time is over 10 seconds, even this enemy starts moving in sin motion.


texts: OpenGL Shader Storage Buffer Objects array length problem

texts:
Ok guys, I think I have a very strange problem.

I have an old laptop, but its HD 6370M currently supports opengl 4.4, so i decided to learn how to use some new features of this platform, so after glVertexAttribFormat, glVertexAttribBinding and so on, I moved to shader storage buffer objects.

I thought they were useful for things like passing light data to shaders, so I tried to make a trivial example working.

the relevant pieces of code in my program are:
C++ creation of buffer

    struct Values
    {
        float val;
    };

    void CreateBuffers()
    {
        glGenBuffers(1, &ssbo);
        glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);

        Values v;
        v.val = 0.3;

        glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(Values), &v, GL_STATIC_DRAW);
        glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
    }

    void Render()
    {
        ...
        glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, ssbo);
        ...
    }

Then in the fragment shader:
GLSL

    struct Values
    {
        float val;
    };

    layout(std430, binding = 0) buffer ssbo
    {
        Values vals[];
    };

And then in the main I could assign a random color to the output variable and I just see my geometry of that color, as expected:

    out vec4 out_color;
    void main()
    {
         out_color = vec4(0.4, 0.3, 0.6, 1); // Yeah, random
    }

Or if I output the value of the variable in the ssbo directly everything works just fine (I see a grayish color on my geometry)

    out vec4 out_color;
    void main()
    {
         out_color = vec4(vals[0].val);
    }

BUT, if I try to get the length of the array with

    vals.length();

in any kind of operation, like in a for loop or simply scale the output color by the length of the array, I get a completely white screen, even if the clear color is set to black, and no geometry is visible at all.
It is important to say that this only happen if in the ssbo i put an array of structures.

I don't think that's relevant, but I'm using Windows 8.1 and MSVC compiler with VS13.

Thanks in advance.

EDIT: I want to say that no error is generated during runtime, the shaders compile successfully and the program is validated and linked

EDIT 2: Ok, now it seems that there is a linking error on the program where the ssbo is, but the infolog says nothing:

    Vertex shader(s) failed to link, fragment shader(s) failed to link.
    Vertex link error: INVALID_OPERATION.
    unexpected error.
    fragment link error: INVALID_OPERATION.
    unexpected error.

Driver bug?


texts: Analyzing movement data for a checkerboard

texts: For a psychology experiment - subject has to learn that the 2D grid is a checkerboard, and collect all the 1s (rewards). How do I test if subjects are actually doing it in the most optimal way -- making least effort for moving from one square to the next by taking smaller steps (or selecting closest reward neighbour). My guess is that if I could simulate a learning algorithm and approximate how long it takes to learn the reward distribution, and then explore it optimally (optimality is defined as a unit of time and exploring closest squares first), I could compare the behaviour.


texts: Efficient system to reach the "parent" variable

texts:
I've been stuck doing this in a very inefficient way and really want to know if there's some design pattern that solves this because it seems like a pretty common problem to have.

I have a system where I have a "world" class then that class has a list of town objects then the town has a list of buildings and buildings have a family. It's simple to for example, know what buildings a town has since the towns have all buildings in a list but what I always end up needing is a way for the building to know what town it is in for example. This can be done by giving buildings a town variable to keep that saved but I have to keep making sure that gets set properly for every stage in the chain which makes a mess of the code. It also messed up saving cause it saved a building in the town's building list but when saving the buildings data, had to save the town's data again since the building has that variable, creating a loop.

I've also tried making static methods that can be reached anywhere that say, a building can use and it will search through all towns until it finds where the building belongs, but that seems very inefficient to me and I've heard the same from others.

Lastly I've tried giving all of these things an ID but that still makes them have to search what "parent" has their ID.

Is there some way of doing this a more correct way? I have a hard time finding good search terms for it so I finally decided to just ask for guidance.


texts:
I'm using Unreal Engine 4.  Currently I ray trace to a surface in game and I'm trying to find the location of the point relative to the surface1 instead of the world.
I have the world position of the origin of the surface and the world position of the impact point.  I also have the X,Y,Z bounds of the object  What I would like to find out is how to get X',Y' position of the hitpoint relative to the upper left corner.  I've tried rotating the hitpoint around the origin to calculate the hitpoint based on refernce Roll, Pitch, and Yaw like so:
FVector RotatePointAroundPivot(FVector hitpoint, FVector pivot, FRotator angles) {
FVector dir = hitpoint - pivot;
FQuat quat(angles);

dir = quat*dir;
hitpoint = dir + pivot;

return hitpoint;
}

But it changes based on the rotation of the plane no matter what I do.
I also tried a very limited technique like so which just assumes it's in one of the correct orientations:
if (actorRotation.Yaw >= 0) {
    xpos = (actorBounds.Y - clickPosition.Y) / (actorBounds.Y * 2) * compscale.X * 1000;
    ypos = (actorBounds.Z + clickPosition.Z) / (actorBounds.Z * 2) * compscale.Y * 1000;
}
else {
    xpos = (actorBounds.Y + clickPosition.Y) / (actorBounds.Y * 2) * compscale.X * 1000;
    ypos = (actorBounds.Z + clickPosition.Z) / (actorBounds.Z * 2) * compscale.Y * 1000;
}

But it's flawed.  All I want is to be able to use the surface like a screen.

Any help would be appreciated.


texts: Stuttering Character When Colliding With Wall XNA 4.0 Help!

texts:
I'm trying to make a platformer game without tiles. I've made a collision handler to handle collision between Player and Stage(platform)and a collision checker, here's the code:

public void handleCollision(GameObject OtherObject)
    {
        if(this.CollidesWith(OtherObject))
        {

            if(OtherObject is Stage)
            {

                float rightEdgeDistance = OtherObject.BoundRect.X - (Position.X + this.BoundRect.Width);
                float leftEdgeDistance = OtherObject.BoundRect.X + OtherObject.BoundRect.Width - Position.X;

                float TopEdgeDistance = OtherObject.BoundRect.Y - (Position.Y + this.BoundRect.Height);
                float BottomEdgeDistance = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height - Position.Y;

                float Left_Right_SmallerDistance = Math.Min(Math.Abs(rightEdgeDistance), Math.Abs(leftEdgeDistance));
                float Top_Bottom_SmallerDistance = Math.Min(Math.Abs(TopEdgeDistance), Math.Abs(BottomEdgeDistance));

                float smallerDistance = Math.Min(Math.Abs(Left_Right_SmallerDistance), Math.Abs(Top_Bottom_SmallerDistance));

                if (smallerDistance == Math.Abs(leftEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X + OtherObject.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(rightEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X - this.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(BottomEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height;
                    Velocity.Y = 0;
                }
                else if (smallerDistance == Math.Abs(TopEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y - this.BoundRect.Height;
                    Velocity.Y = 0;
                }
            }
        }
}

My collision checker:

public bool CollidesWith(GameObject OtherObject)
    {
            return BoundRect.Intersects(OtherObject.BoundRect);
    }

Here's my inputHandler method for the Player class:

public void inputHandler(GameTime gameTime)
    {
        Velocity = Vector2.Zero;

        if (Keyboard.GetState().IsKeyDown(Keys.W) )
        {
            Velocity.Y -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else if (Keyboard.GetState().IsKeyDown(Keys.S) )
        {
            Velocity.Y += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else
            Velocity.Y = 0;

        if (Keyboard.GetState().IsKeyDown(Keys.A) )
        {
            Velocity.X -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else if (Keyboard.GetState().IsKeyDown(Keys.D) )
        {
            Velocity.X += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else
            Velocity.X = 0;

    }

And here's my code for the Update method in Player:

public void Update(GameTime gameTime,List<Stage> lstOtherObject)
    {
        inputHandler(gameTime);
        foreach (GameObject OtherObject in lstOtherObject) { handleCollision(OtherObject); }

        Position += Velocity;
    }

This works, if I don't continue to press the keys in the bounded direction. If I do, it will stutter in and out of the platform bounds.
Like this:
It goes a bit into the grey platform
and then it goes out of the grey platform to the intended place.
Can someone help? I want to learn, but I cant seems to figure out whats wrong with this.I tried many things, but still I can't achieve what I want, that is for the player to stop when it reaches the bounds of the platform and never going into it.Appreciate if someone can bring a clear solution and explanation to this. Thanks.


texts:
I have some code for rendering a button in an application and I want to clip the text if it's wider than the button itself. Here a bit of code to describe what I'm doing:

GL.Enable(EnableCap.ScissorTest);
GL.Scissor(Frame.X, ScreenSize.Y - Frame.Y - Frame.Height, Frame.Width, Frame.Height);

RenderRect(Frame, Color.Red);
RenderText(Text, Color.White);

GL.Disable(EnableCap.ScissorTest);

I'm using OpenTK and QuickFont as the text rendering library. The main problem is, the rectangle gets clipped just like it should, but the text will render outside the scissor region if it's too long. I wondered what QuickFont was actually doing during the text rendering, but I couldn't find anything else than some GL.PushMatrix and GL.LoadIdentity calls that could interfere. Are these functions resetting the scissor test? Would a GL.PushMatrix call make it so that it would be possible to render outside the clipping rectangle?


texts:
There are many tutorials to learn GLSL, Cg, HLSL... with classical samples as bump mapping, toon-shading...

But is there a shaders directory?

a website where i can share my shaders
search shader by name, description and implementation


texts:
I've seen that the Quake 3 Engines uses QVMs and DLLs for the gamelogic. Unity uses some kind of Component-Entity system.

My question is basicly:
What's a good way to keep the engine seperated from the game logic itself, without having such things as "QVMs" or Component Systems.

The problem is, all my  current approaches on creating an "seperation" of the logic leads me in having kinda unflexible code or code that has to deal more with the engine than the logic itself.

I know this can be seen as too broad, but this problem is bothering me for a week yet and I can't seem to find a way to fix this.

EDIT, see first comment:
To be honest I tried only 3 approaches.

My approache number one was for example to programm an "App Class" creating and handling events:

class DXApp
{
private:
  HWND ... // All that windows stuff
public:
  virtual void Render();
  virtual void Update( float fTime );
};

On top of that I created little abstraction layers ( abstract Buffers then Model classes based on them ) which ended in the code dealing more with the engine than the logic itself. E.g. I am asking the window for User Input, which makes use the explicit object(-methods ).

My second approach was to create an GameState based logic with ManagerClasses which are calling my methods. This made my game logic yet again pretty dependent of the engine.

My third approach however, was to use an scripting engine. This made my end up in mapping many classes to Python classes ( the engine was calling the scripts! ). The code wasn't clean at all.
On top of that, the more function calls I used the slower the game worked. But the code was rather independent and had not to deal with any engine specific tasks.

I think this problem is  more of a architectural matter.

I hope I could explain good what bothered me, if not please post below in the comments.


texts: Unity - Setting a sprite animation idle to a specific frame and transition smoothly

texts:
I'm new to Unity. I have built an animation with a 2d spritesheet and now I want to transition between idle and walking.

Idle is my frame 1 (or any other frame) and the whole spritesheet animation is running.

When I create the animatorcontroller, I'd set idle as no animation and walking as the animation from the spritesheet, I then assign conditions as paramenter, but when a paramente change, the transition is not smooth, it skips back to the first frame.

How can I make a transition that would, when stopping, continue to animate until the idle frame has been reached, and then stop?


texts: Rotate around a 3d Object (Software Renderer)

texts:
I have a simple 3d software renderer (SDL / C++) which can load a 3ds Model and render it (shaded) and rotate it around X Y Z - Axis.
Now I would like to rotate / move around the object, meaning, the object itself stands still, and everything in the scene is displayed from the angle of the view. Is that what a camera in 3d engines does, and how would I implement something like this ?

(No OpenGL / DirectX is used, just plain software)


texts: How to move through a game object - while getting the normal of the initial contact

texts:
In Unity, how can I detect a collision between two game objects, but have them pass through one another, i.e. not block each other?
Specifically, I need the collision normal provided by the Collision2D object that comes with the OnCollisionEnter2D method. But I want to be able to move through the object that detected the collision, not get blocked by it.
PS: Checking the Is Trigger checkbox would mean the argument passed into the trigger method no longer contains the collision normal!


texts: How to shade a texture two different colors?

texts:
To give an example of what I'm asking about, I'll use Saints Row 3 since I've been playing that lately.  In that game you can customize your looks and your car's appearance a lot.  Your coat can have a primary color and a trim color.  Your car can have a primary color and a stripe color, etc.

Is there just a single coat texture that is being shaded two different colors somehow or are they overlaying a transparent second texture for the trim/stripes that gets shaded differently?

If it's just one texture I'd like to know how it's done.

If it's two different textures it seems like it's a waste of space.  The second texture would be the same size as the first one but mostly transparent if you just wanted to lay it on top of the first one.  Or are they just carefully positioning a second, smaller texture so that it aligns properly with the first one?


texts: How do I stop my game character from sliding on the ground?

texts:
I am working with the latest version of Unity (2019.3.4f1) at the time of writing.

I have some terrain, some blocks as obstacles and a player character with some mouse driven motion controls. You click the mouse on the terrain and the player character turns and walks in the direction of where you clicked until they reach their destination, so far so good.

I have recently added a rigidbody component and a box collider on the player character in order to get the character to 'bump' into walls and not simply walk through them like a ghost. This aspect is working, unfortunately the character keeps sliding on the ground. Since the terrain is at a bit of a slope the character just slides forever away as if they were standing on oil. I've been trying different solutions to get the character to stop doing this when they are not moving but nothing seems to work.

These are the things that I have tried thus far:

Increasing the Mass of the Rigidbody - No effect, actually I think the character is sliding even faster.

Increasing the Drag - This was working but the moment I added an X and Z constraint on Freeze Rotation it just stopped working and I need those constraints because I don't want the character to fall over.

Adding a Physic Material to the Box Collider - This doesn't seem to be doing anything. the physic material I created has friction values around 300 and the character is still sliding away on oil.

These are the settings for the rigidbody and the box collider currently on the character.

This is the Physic Material that I added to the player character's box collider.

This is the code that I am using to move the character.

void FixedUpdate()
{
    switch (currentState)
    {
        case State.Idle:
            break;
        case State.Moving:
        case State.Sneaking:
            MoveTowardsTarget();
            break;
    }

    transform.position = new Vector3(transform.position.x, grid.GetHeightAtCoord(transform.position), transform.position.z);
}

private void MoveTowardsTarget()
{
    if (currentState == State.Moving) _currentCrouch = 0.0f;
    else if (currentState == State.Sneaking) _currentCrouch = 1.0f;

    Vector3 position = transform.position;
    _currentPosition = position;
    _currentPosition = new Vector3(_currentPosition.x, grid.GetHeightAtCoord(position), _currentPosition.z);

    float distanceToDestination = Vector3.Distance(_currentPosition, currentDestination);
    float targetSpeed;

    if (distanceToDestination > _strollDistance && distanceToDestination < _hustleDistance) targetSpeed = _strollSpeed;
    else if (distanceToDestination > _hustleDistance) targetSpeed = isRunModeOn ? _runSpeed : _hustleSpeed;
    else
    {
        targetSpeed = 0;
        currentState = State.Idle;
    }

    if(targetSpeed > 0) TurnTowardsTarget(distanceToDestination);

    _currentSpeed = Mathf.Lerp(_currentSpeed, targetSpeed, Time.deltaTime * _accelleration);
    transform.Translate(Vector3.forward * (Time.deltaTime * _currentSpeed));
}

private void TurnTowardsTarget(float distanceToDestination)
{
    float currentRotation = transform.eulerAngles.y;

    Vector3 normalizedAngle = (transform.position - currentDestination).normalized;
    float angle = -(Mathf.Atan2(normalizedAngle.z, normalizedAngle.x) * Mathf.Rad2Deg + 180);

    Vector3 targetAngle = new Vector3(0.0f, angle + 90, 0.0f);
    Vector3 currentAngle = transform.eulerAngles;

    currentAngle = new Vector3(
        Mathf.LerpAngle(currentAngle.x, targetAngle.x, Time.deltaTime * _turnSpeed),
        Mathf.LerpAngle(currentAngle.y, targetAngle.y, Time.deltaTime * _turnSpeed),
        Mathf.LerpAngle(currentAngle.z, targetAngle.z, Time.deltaTime * _turnSpeed));

    _currentRotation = CameraOrbitManager.ClampAngle(currentRotation - currentAngle.y, -360, 360);

    transform.eulerAngles = currentAngle;
}

Can someone please tell me what I am missing? Why does the player character keep sliding away?


texts: How can I find the position of a corner of a transformed sprite in SFML?

texts:
I need help with calculating the end points of a stick (a sprite) in my stick game.

First, I set up it's position by some coordinate (x,y) after that I rotate it by theta degrees.

I know the width and height (427, 17), but I can't figure out how to calculate it's end points after the rotation (I need them for intersect detection algorithm).

Moreover, I can't figure out how to detect when I clicked on it with the mouse, because getGlobalbounds.contains(mouse) gives me its bounding box, but I want to detect that I was clicked exactly on the entity..


texts: What mistake did I make? Source engine reskin issues

texts: Here is a reskin of the Half Life 2 Wallace Breen model that I made for a mod I am developing, but the checkerboard on the suit is very odd. All my other skins have no issue, but this skin has checkerboards under certain lighting situations. When mat_fullbright 1 is on, chekerboards do not show. When dynamic shadows and shading in on, or when mat_fullbright 0 is in use, the suit checkerboards.


texts: Can I use clipping with Unity Sprite in NGUI?

texts: I used NGUI free version (2.7) with Unity 4.3. I have tried to use clipping to restrict the area of viewer by using clipping to hide some content of Unity Sprite. However, it did not work. If it's NGUI own sprite, it worked. Is there a way to use clipping with Unity Sprite? I have done some asset with animation with unity sprite (2D) but it cannot be clipped.


texts: How can I reduce writes-per-second when saving player data to a database?

texts:
Consider a game where the player has some profile or save data stored in a database. What I want to understand is, for things that effect the users score or level, there could be so many factors that this has to be persisted to the database and if it is, this could be many writes per second per player potentially, which could be expensive or slow.

How can I reduce the load on the database while still maintaining critical player information?


texts:
I've done some shader programming some time ago but only simple stuff. I'm especially interested in how do you manage shaders? Do you just write one of each kind, or do you need more of them? If so, how exactly do you split and managed them?

Also I've recently read that all the transformation matrix operations I used in OpenGL(glPushMatrix, etc) are now deprecated and you need to manage your own matrices.Is that something you do in a vertex shader and how would I go about doing it correctly?

Suggestions for books about this topic will be highly appreciated.

Thank you.


texts:
I'm playing around with a bomberman clone to learn game-developement.

So far I've done tiles, movement, collision detection, and item pickup. I also have pseudo bombplacing (just graphics and collision, no real functionality).

I've made a jsFiddle of the game with the functionality I currently have. The code in the fiddle is very ugly though. Scroll past the map and you find how I place bombs.

Anyway, what I would like to do is an object, that has the general information about bombs like:

function Bomb(){
  this.radius = player.bombRadius;
  this.placeBomb = function (){
    if(player.bombs != 0){
      // place bomb
    }
  }
  this.explosion = function (){
  // Explosion
  }
}

I don't really know how to fit it into the code though. Everytime I place a bomb, do I do var bomb = new Bomb(); or do i need to constantly have that in the script to be able to access it.

How does the bomb do damage? Is it as simple as doing X,Y in all directions until radius runs out or object stops it? Can I use something like setTimeout(bomb.explosion, 3000) as timer?

Any help is appreciated, be it a simple explanation of the theory or code examples based on the fiddle. When I tried the object way it breaks the code.

Update: I now place bombs, and after a certain amount of time delete it depending on the position I placed it. But if I place a bomb before the first bomb explodes it only deletes one of them (obviously since bombX and bombY has changed since the first was placed).

Now i need to know how to fix this issue, maybe create a new array with all of the bomb positions? What's the best way of doing this?

Current code:

function placeBomb(){
    if(placebomb && player.bombs != 0){
        map[player.Y][player.X].object = 2;
        bombX = player.X; bombY = player.Y;
        placebomb = false;
        player.bombs--;
        setTimeout(explode, 3000);
    }
}
function explode(){
    alert('BOOM!');
    delete map[bombY][bombX].object;
    player.bombs++;
}


texts: WP7 emulator + Microsoft.Advertising.Mobile.Xna.dll = 'System.IO.FileLoadException' occurred in mscorlib.dll

texts:
I've downloaded Microsoft Advertising SDK for WP7, added reference to Windows Phone Game project, and now when I'm trying to run the game I get this in Output:

'taskhost.exe' (Managed): Loaded 'mscorlib.dll'
'taskhost.exe' (Managed): Loaded 'System.Windows.RuntimeHost.dll'
'taskhost.exe' (Managed): Loaded 'System.dll'
'taskhost.exe' (Managed): Loaded 'System.Windows.dll'
'taskhost.exe' (Managed): Loaded 'System.Xml.dll'
'taskhost.exe' (Managed): Loaded '\Applications\Install\B2719AD1-5A3C-40BE-A114-7E56C19E22D6\Install\TheGame.dll', Symbols loaded.
A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll
The thread '<No Name>' (0xd4b004e) has exited with code 0 (0x0).
The program '[229048418] taskhost.exe: Managed' has exited with code 0 (0x0).

If the reference is removed, game launches normally again.

What might be the possible solution to fix this?


texts:
I develop in OpenGL using C# as programming language.
I want to draw some text on the screen. For this i created a texture that contains all the characters.

Now i am not sure how to continue. I can draw now every character like this:

Gl.glBegin(Gl.GL_QUADS);
{
    Gl.glTexCoord2f(posX, posY);
    Gl.glVertex2f(-1, -1);

    Gl.glTexCoord2f(posX + size, posY);
    Gl.glVertex3f(1, -1);

    Gl.glTexCoord2f(posX + size, posY + size);
    Gl.glVertex3f(1, 1);

    Gl.glTexCoord2f(posX, posY + size);
    Gl.glVertex3f(-1, 1);
}
Gl.glEnd();

posX and posY contain the start position of the character in the character-texture. size is the size of the character in the texture.

This method needs a lot of draw calls. I mean i draw lots of quads but i only need one where i can put all the text on it. How can i improve my code?


texts: What are some ways to keep the player engaged in an endless game?

texts:
An endless game consists of the same gameplay mechanics repeated over and over. You have to keep doing mostly the same things as long as you can.

So it is quite easy to make players bored of your game. What are some concepts that one could implement into the game design to keep the player engaged?

To be more specific, my game is an endless tapping game where you have to tap rockets to make them explode into fireworks, and sometimes on falling meteors too.


texts: Part of model in Unity is inside out but not in Blender?

texts:
I've downloaded this asset and it looks perfectly fine in preview, and even in blender.

But when I import it in Unity, one of its shoulder is inside out, even after making all faces double sided.

I also tried switching the normal mode in the import settings to Calculate.

What causes this issue and how could I fix this?


texts: Find the nearest control points either side of a Catmull Rom spline segment

texts:
There is a formula for evaluating a Catmull Rom spline segment at time 't' found here.

The problem with this is that it requires finding the two control points either side of the segment to evaluate.

Is there a formula for finding those two control points?

As a alternative I considered utilising some kind of algrorithm for finding the nearest values either side of a given value:

float lowerNearest = float.MaxValue;
float upperNearest = float.MinValue;

int numElements = array.Length;

for (int i = 0; i < numElements; ++i)
{
    float dif = index - array[i].Index

    if (dif > 0)
    {
                     lowerNearest = Math.Min(lowerNearest, dif)
    }
    else
    {
         upperNearest = Math.Max(upperNearest, dif);
    }
}

However I'm not sure what values I should be comparing as the control points are only vectors and felt that it was probably the incorrect way to approach this problem.


texts: Get back or delete an existing OpenGL object, then change it and draw at new. How?

texts:
With OpenGL i'm drawing for example a circle.

Can i take this drawn circle back out of the window and change something and then draw it back on the window?

Or can i /have to delete it and then draw it new with other properties?

Do someone have me a link etc how to do something like this?

edit
it is just about 2D objects


texts: Can textures change between resolutions?

texts:
I'm a beginner in game design and textures have been bothering me. How do they work in video games? Here's what I mean.
Can textures change between resolutions in settings?
Or is it tied to screen resolution? As in your game has 4k textures but the user sets the display to 1080P. And if this is true then what resolution should the textures you put in the game be?


texts: How to draw a smooth circle in Android using OpenGL?

texts:
I am learning about OpenGL API on Android. I just drew a circle. Below is the code I used.

public class MyGLBall {

private int points=360;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;

//centre of circle

public MyGLBall(){

    vertices=new float[(points+1)*3];
    for(int i=3;i<(points+1)*3;i+=3){
      double rad=(i*360/points*3)*(3.14/180);
      vertices[i]=(float)Math.cos(rad);
      vertices[i+1]=(float) Math.sin(rad);
      vertices[i+2]=0;
    }
      ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
      bBuff.order(ByteOrder.nativeOrder());
      vertBuff=bBuff.asFloatBuffer();
      vertBuff.put(vertices);
      vertBuff.position(0);

}

public void draw(GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(0, 0, 0);
//  gl.glScalef(size, size, 1.0f);
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
 }

 }

It is actually taken directly from here
The circle looks pretty good. But now I want to make the boundary of the circle smooth. What changes do I need to make to the code? Or do I need to use some other technique for drawing the circle?

Thanks.


texts: Is it possible to create sqlite database only for android in LIBGDX game?

texts:
I want to know if I can just implement sqlite database for android in libgdx game?
Also if this is not possible then may I know the simple way to integrate libgdx game to just store scores in sqlite database.
I dont want to use preference or jason because I have to get last stored scores and then level wise comparison of scores.


texts: How to mitigate when applying horizontal force to a rigidbody seems to overpower gravity?

texts:
I've started testing movement using the example code in this answer of making a body accelerate to a target velocity
    private void FixedUpdate()
    {
        Vector2 input = GetInput();

        if (Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon)
        {
            Vector3 desiredVelocity = new Vector3(input.x * speed, 0f, input.y * speed);

            Vector3 delta = desiredVelocity - body.velocity;
            Vector3 acceleration = delta / Time.deltaTime;

            if (acceleration.sqrMagnitude > maxAccel * maxAccel)
            {
                acceleration = acceleration.normalized * maxAccel;
            }

            body.AddForce(acceleration, ForceMode.Acceleration);
        }
    }

and I've encountered the following curious behavior:
https://imgur.com/snGyVYK
When moving the body by applying force, the body seems to levitate as if gravity is not being applied. It actually is being applied but it seems as if the force being applied to the body is overriding the force of gravity because as soon as I let go of the movement keys the body suddenly drops. I am not applying any force on the y axis so I'm not sure what exactly is at play here. What is going on here and what can I do to mitigate this behavior?


texts: has anyone used or heard of a good selenium-like toolset for doing automated UI testing with Flash? I would ideally like to have the ability to record and playback events against my game and integrate this into our build server.


texts: My runtime mesh is not being created where it's vertices are located, need help

texts:
I'm trying to create a quad at runtime and I'm encountering an issue where the mesh does not show up in the scene where it's vertices where set. In the following picture you can see the ship, and to the far right the mesh.

The 4 white dots around the ship where drawn after the mesh was made using the 4 vertices of the mesh.

My Code:

//Handles the method calls for the mesh creation
private void BoundingMeshCreation()
{
    Quaternion currentRotation = ResetPosition(new Quaternion(0, 0, 0, 0));
    BoundingPointsType boundingPoints = DetermineBounds();
    Mesh boundingMesh = CreateBoundingMesh(boundingPoints);
    AssignMesh(boundingMesh);
    ResetPosition(currentRotation);
}

//Creates the mesh filter and assigns the mesh
private void AssignMesh(Mesh boundingMesh)
{
    MeshFilter newMeshFilter = gameObject.AddComponent<MeshFilter>();
    newMeshFilter.mesh = boundingMesh;

    VectorLine testPoint = new VectorPoints("testPoint", boundingMesh.vertices, null, 5);
    testPoint.Draw3D();
}

//Creates a bounding mesh for the unit
private Mesh CreateBoundingMesh(BoundingPointsType boundingPoints)
{

    Mesh boundingMesh = new Mesh();
    boundingMesh.name = "Bounding Quad";

    Vector3[] vertices = new Vector3[4]
    {
        boundingPoints.LowerLeftPoint,
        boundingPoints.LowerRightPoint,
        boundingPoints.UpperRightPoint,
        boundingPoints.UpperLeftPoint
    };

    int[] triangles = new int[6]
    {
        0,
        2,
        1,

        0,
        3,
        2
    };

    boundingMesh.vertices = vertices;
    boundingMesh.triangles = triangles;

    return boundingMesh;
}

//Resets the units rotation to the specific quaternion and returns the quaterion from before the reset. Bit of a hack for now to make sure that the original box is the proper size.
private Quaternion ResetPosition(Quaternion toResetTo)
{
    Quaternion currentRotation = transformV.rotation;
    transformV.rotation = toResetTo;
    return currentRotation;
}

//Determines and returns the bounding box points
private BoundingPointsType DetermineBounds()
{
    Vector3 maxBounds = childSprite.GetComponent<Renderer>().bounds.max;
    Vector3 minBounds = childSprite.GetComponent<Renderer>().bounds.min;

    BoundingPointsType boundingPoints = new BoundingPointsType(new Vector3(maxBounds.x, 1, maxBounds.z),
                                                               new Vector3(minBounds.x, 1, maxBounds.z),
                                                               new Vector3(maxBounds.x, 1, minBounds.z),
                                                               new Vector3(minBounds.x, 1, minBounds.z));
    return boundingPoints;
}

I've even tried manually setting the vertices like the following:

    Vector3 UpRight = transformV.position;
    Vector3 UpLeft = transformV.position;
    Vector3 LowRight = transformV.position;
    Vector3 LowLeft = transformV.position;

    UpRight.z += 1;
    UpRight.x += 1;

    UpLeft.z += 1;
    UpLeft.x -= 1;

    LowRight.z -= 1;
    LowRight.x += 1;

    LowLeft.z -= 1;
    LowLeft.x -= 1;

    Vector3[] vertices = new Vector3[4]
    {
        LowLeft,
        LowRight,
        UpRight,
        UpLeft
        //boundingPoints.LowerLeftPoint,
        //boundingPoints.LowerRightPoint,
        //boundingPoints.UpperRightPoint,
        //boundingPoints.UpperLeftPoint
    };

I'm at a loss, and have no idea what I'm doing wrong. My dynamic meshes seem to work perfectly fine for everything else in the game.

Thanks.


texts: Can I use copyrighted music in my video game, even though it's free to play?

texts: I'm making a video game, and thought of making a boss theme, where I use an 8bit remix and the original instrumentals of the song Chop Suey. I'm already in contact with the 8bit versions creator, but I'm not sure if I can use the original instrumental, without my game being taken down.


texts: Simple mobile multiplayer game. TCP/UDP?

texts:
I'm tying to dive into multiplayer game programming.

The game is quite simple, it's a 2D scroller mobile game, the player need to touch the screen in order to move 1 step and it could contain up to 4 players at max. 1 of the player could create a room for other players to join.

I was thinking that I would use TCP for this and will only send packets when 1 of the player trigger an event like moving or exiting the game. Is my approach is correct? Since from what I've read, many games are created in UDP instead of TCP.

In case of UDP, what is sent between the clients and the server? The position of each entity in the game at a fix time interval?

I'm really new multiplayer programming. I'd appreciate if someone would share their story.

Thank you.


texts: Separate data tables for different item types?

texts: I have two types of items in my game, consumables, and equipment. For my database, should I store them in two different tables, or all in one big items table?


texts:
I am using Spritefont in my game and I have downloaded a .ttf font and installed it on my machine. I am now using this font in my game.

My question is if this game is run on another machine will the .ttf font need to be installed on that machine to work?


texts: My xna game is running at about 70-90fps and it looks laggy at this fps.  I'm using fraps to record the fps and I have a 120hz monitor, over 120hz looks fine but I can't understand why it feels like it's lagging so much at high fps :/.


texts:
I'm writing a rudimentary 2D engine and am wondering what the proper or generally accepted order is for handling graphics, user input, sounds, and then other systems like physics.

If you have written an engine, please explain your order and why you picked that particular order.


texts: GLSL link fails with C9999 (too many buffer declarations?)

texts:
I'm receiving a C9999 (*** exception during compilation ***) linker error for an OpenGl 4.6 compute shader. It seems to be related to the number of SSBOs I have declared (14 separate declarations), but it really doesn't seem like it should be a problem, given that my GTX 1070 has 96 buffer binding locations.
None of the names are reserved keywords, and I'm not using double underscores. This has happened to me before, but I've worked around it by managing to split my code into separate shaders with fewer buffer declarations.
I'm finally asking about it because, for performance reasons, I'd really rather not split this up.

This is all the information the driver gives me in this case.
Update:
While I have received that error for buffers in the past, now I've narrowed this down to the following:

buffer _elementmap   { uint elementmap[]; };

void element_insert(vec4 element)
{
    uint hash = get_hash(element);
    uint spot = 2 + (hash % (elementmap.length() - 2));
                                        ~~^

    uint pos = atomicAdd(elementmap[0], 1);

    [...]
}

Calling length() on that buffer produces the error for me. Seems like a driver bug. If I pass the length in as a separate buffer or a uniform, it works fine.
Additionally, I have a separate much simpler compute shader that doesn't include this particular function that uses .length() on that same declaration that does work.


texts:
I'm creating an Android game and I want everyone who plays it -- no matter the size or shape of their screen -- to see the same 480x800 playfield but, depending on the actual resolution of their screen, scaled to fit their screen while maintaining the correct aspect ratio using letterboxing or black bars on the edges of the screen to fill in the gaps on the sides/top/bottom.

I'm using Canvas to develop my game but I don't know where to start, or have any idea of best practices for accomplishing this. Could someone enlighten me?

UPDATE: What I had in mind was using different image resources from hdpi/ldpi/mdpi resource folders and drawing them so bigger screens are restricted to the aspect ratio still but will be higher resolution. So drawing to a 480x800 bitmap won't work in my situation.


texts: Good Way to Handle Scheduled Events in Mobile Multiplayer Strategy Games

texts:
I am developing a mobile strategy game like Clash of Kings. There are scheduled events in the game (like constructing buildings, recruiting troops, and attacking to other settlements) which happen when a specified time comes.

I was wondering what is a good way to handle these kind of events?

In my current design, I am using AWS products everywhere. A load balancer redirects a user request to one of the http servers which runs a nodejs code. Nodejs script creates an event record which contains required data to do the event later.(For example it contains number of soldiers, defender settlement, event time etc. in case of attacks.) It then inserts a record to a table called Events in DynamoDB(NoSQL DB in AWS). DynamoDB supports something like a callback system using AWS Lambda and DynamoDB Streams, which basically allows me to run a serverless code whenever new data is inserted to a table. I am planning to write a lambda function that connects to an internal worker computer through an internal load balancer, and gives event data to the worker for it to process. Worker runs a java code, and uses a priority queue to hold events. At each second, it pops events whose time has come from priority queue and spawns threads to handle them. Threads does the required calculations, inserts the results to DynamoDB, and possibly sends notifications to users through AWS SNS.

The reason I did not connect directly to workers from http servers was to use http servers to answer user queries as fast as possible, and carrying load to the background system.

Do you think handling timed events like this is a good solution? Is there a standard or a better way to approach this problem?

My main concern is that I will be running a loop that sleeps for 1 sec and polls the priority queue. If I was able to design a callback like system, which calls a function when the event time comes, I would be using less resources. Is there such an architecture or a system that makes this easy?

As an alternative, I read that some browser strategy games do not have background processes, and they do available events on user requests. Before handling each request, they run a code that does due events. Would that be a better approach?

As a footnote, I want to develop a system that is easily scalable which can support number of users in the order of millions.


texts:
I have some old XNA 3.0 projects that used stuff that has totally been changed in XNA 4.0.

Really I just want to revisit some of my old code, dust it off and refactor it.

Can XNA 3.0 and XNA 4.0 be installed together in Visual Studio 2010, or will there be problems?

Should I just install C# Express Edition 2008 with XNA 3.0, and work with my old projects that way?


texts: Debugging an AMD GPU specific problem without an AMD GPU

texts:
I've recently started to receive reports from users that I game I'm working on isn't rendering properly on AMD GPUs. I'd like to track down the problem and fix it, but I'm a hobby developer just using my own computer and I don't have an AMD GPU.

Do I have any options here besides going out and buying another graphics card? Perhaps some sort of emulator or a cloud compute service with AMD GPUs? I've looked at the major cloud compute providers (AWS, Google Cloud and Azure) but they all seem to offer only Nvidia GPUs.


texts: How to quit current state animation correctly?

texts:
I've a 'classic' humanoid player with an animation controller and some animations.

This is the code i'm managing state changin

        float h = CrossPlatformInputManager.GetAxis ("Horizontal");
        if (h < 0) {
            m_Animator.SetTrigger ("LeftWalking");
        }
        else if (h > 0) {
            m_Animator.SetTrigger ("RightWalking");
        }
        else if (m_CharacterController.velocity.magnitude != 0) {
            m_Animator.SetTrigger ("Walking");
        }
        else if (m_Jumping) {
            m_Animator.SetTrigger ("Jump");
        }
        else {
            m_Animator.SetTrigger ("Idle");
            m_Animator.ResetTrigger ("Walking");
            m_Animator.ResetTrigger ("LeftWalking");
            m_Animator.ResetTrigger ("RightWalking");
            m_Animator.ResetTrigger ("Jump");
        }
    }

My problem is that after i stop to press my "forward" button (that make my player walking), the walking animation continue to play itself till the end.

This is my state machine

This is options of Walking to Idle state

I'm pretty sure I've to "play" with HasExitTime and/or FixedDuration but i'm not sure...


texts: Trying to extract file icons and use as a sprite texture

texts:
I'm trying to extract file icons from the files inside a folder (eg: Program Files), and have them set as my Sprite's texture. I extracted the file icons, converted them to Bitmaps and then to byte array, and call the LoadImage(byte[] byte) function in my Sprite object. But when I test, the textures become the image belows. Any idea how to fix this? I just want to set my sprites texture as the extracted file icon, I'm creating something similar to a file explorer.

this is the result that i get

this is what I should get if I navigate to the notepad++ folder (eg : "C:\Program Files(x86)\Notepad++\")

this is my settings for the texture (supposedly, later being replaced with the extracted icons)

Here's my code

public UnityEngine.UI.Image targetImg;
public void Load(string directory)
{
    Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(directory);
    Bitmap bmp = icon.ToBitmap();
    targetImg.sprite.texture.LoadImage(ImageToByte(bmp));
}

public static byte[] ImageToByte(Bitmap img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}


texts: Cannot change main camera's inital position in Unity inspector

texts:
I modify the Unity Platformer Minigame and want the main camera to display less of the lower part of the view. The Y coordinate in the inspector of the main camera is always -0.2777786 and I cannot change it.

I think what I want to is very simple so it should not take several hours of confusion.


texts: problem with frustum AABB culling in DirectX

texts:
I am currently working on a project with a few friends, and I am trying to get frustum culling working.  Every single tutorial or article I go to shows that my math is correct and that this should be working.  I thought maybe posting here, somebody would catch something I could not.  Thank you.

Here are the important code snippets

     /create the projection matrix
void CD3DCamera::SetLens(float fov, float aspect, float nearZ, float farZ)
{
 D3DXMatrixPerspectiveFovLH(&projMat, D3DXToRadian(fov), aspect, nearZ, farZ);
}

//build the view matrix after changes have been made to camera
void CD3DCamera::BuildView()
{
 //keep axes orthoganal
 D3DXVec3Normalize(&look, &look);

 //up
 D3DXVec3Cross(&up, &look, &right);
 D3DXVec3Normalize(&up, &up);

 //right
 D3DXVec3Cross(&right, &up, &look);
 D3DXVec3Normalize(&right, &right);

 //fill view matrix
 float x = -D3DXVec3Dot(&position, &right);
 float y = -D3DXVec3Dot(&position, &up);
 float z = -D3DXVec3Dot(&position, &look);

 viewMat(0,0) = right.x;
 viewMat(1,0) = right.y;
 viewMat(2,0) = right.z;
 viewMat(3,0) = x;

 viewMat(0,1) = up.x;
 viewMat(1,1) = up.y;
 viewMat(2,1) = up.z;
 viewMat(3,1) = y;

 viewMat(0,2) = look.x;
 viewMat(1,2) = look.y;
 viewMat(2,2) = look.z;
 viewMat(3,2) = z;

 viewMat(0,3) = 0.0f;
 viewMat(1,3) = 0.0f;
 viewMat(2,3) = 0.0f;
 viewMat(3,3) = 1.0f;
}

    void CD3DCamera::BuildFrustum()
{

 D3DXMATRIX VP;
 D3DXMatrixMultiply(&VP, &viewMat, &projMat);

 D3DXVECTOR4 col0(VP(0,0), VP(1,0), VP(2,0), VP(3,0));

 D3DXVECTOR4 col1(VP(0,1), VP(1,1), VP(2,1), VP(3,1));

 D3DXVECTOR4 col2(VP(0,2), VP(1,2), VP(2,2), VP(3,2));

 D3DXVECTOR4 col3(VP(0,3), VP(1,3), VP(2,3), VP(3,3));

 // Planes face inward
 frustum[0] = (D3DXPLANE)(col2);    // near
 frustum[1] = (D3DXPLANE)(col3 - col2);  // far
 frustum[2] = (D3DXPLANE)(col3 + col0);  // left
 frustum[3] = (D3DXPLANE)(col3 - col0);  // right
 frustum[4] = (D3DXPLANE)(col3 - col1);  // top
 frustum[5] = (D3DXPLANE)(col3 + col1);  // bottom

 // Normalize the frustum
 for( int i = 0; i < 6; ++i )
  D3DXPlaneNormalize( &frustum[i], &frustum[i] );

}

    bool FrustumCheck(D3DXVECTOR3 max, D3DXVECTOR3 min, const D3DXPLANE* frustum)
{
 // Test assumes frustum planes face inward.

 D3DXVECTOR3 P;
 D3DXVECTOR3 Q;
 bool ret = false;

 for(int i = 0; i < 6; ++i)
 {
  // For each coordinate axis x, y, z...
  for(int j = 0; j < 3; ++j)
  {
   // Make PQ point in the same direction as the plane normal on this axis.
   if( frustum[i][j] > 0.0f )
   {
    P[j] = min[j];
    Q[j] = max[j];
   }
   else
   {
    P[j] = max[j];
    Q[j] = min[j];
   }
  }

  if(D3DXPlaneDotCoord(&frustum[i], &Q) < 0.0f  )
   ret = false;
 }
 return true;
}


texts:
I have an array of nodes, i need to get a specific Node from this array in the InputListener event using Actor hit()..

I have multiple menu items (Buttons, Levels) but the touch event not working.
This is what i tried so far:

 public Actor hit(final float x, final float y, final boolean b) {
    ...
        for (int i = this.nodesList.size() - 1; i >= 0; --i) {
            final Node node = this.nodesList.get(i);
            if (node instanceof SpriteNode) {
                SpriteNode newNode = (SpriteNode) node;
                if  (newNode.anchornsform.det() != 0.0f) {
                    final Affine2 inv = newNode.anchoreansform.inv();
                  ...
                }
            }
        }
    }
    return myactor;
}

Please help, if you have a better solution I'm open to any suggestions.

Thank you


texts: Application is crashing with Ogre::ItemIdentityException

texts:
I am new to OGRE and i am trying to create a 3D line using following tutorial: http://www.ogre3d.org/tikiwiki/Line+3D
and application is crashing with following exception Ogre::ItemIdentityException.


texts: 3rd person camera rotate around player with mouse

texts: I'm trying to make a 3rd person camera for a game with THREE.js and Physijs (if that's important), and so far I have set it up so that the camera follows behind the player using cos and sin etc. but I want to make it so that the user can rotate the camera in any direction around the player (and zoom in and out of course), and then when the player starts moving slowly lerp/reset the camera position to behind the player, but I'm not sure how to do this in THREE.js, I don't think OrbitControls let's it reset the position (or does it)?


texts: XNA Diffuse Shader Issue. Edge lighting problem. Image Attached

texts:
As you can see in this image the diffuse shading is working correctly in some places but in other places such as the the bottom of the sphere you can see the squares/triangles of
the mesh.

Any idea what would be causing this? Let me know if you need anymore information related to
code. I can upload my normals calculations and shader effect if required.

EDIT:
Here's a link to the shader I'm using http://pastebin.com/gymVc7CP

Link to normals calculations: http://pastebin.com/KnMGdzHP

Seems to be an issue with edge lighting. Can't seem to see where I'm going wrong with the normals calculations though.


texts: Prefab disables its script when a clone is instantiated

texts:
A clone of a cube is spawned when it is destroyed, however the clones disable the script in the editor (example: http://gfycat.com/SnarlingScornfulEgg). Used the exact same script for a different kind of 'enemy' and it worked as intended.

Relevant part of script:

function Start () {
    health = 100;
}

function Update () {
    if(health <= 0){
        Dead();
    }
}

function OnCollisionEnter (col : Collision) {
    if(col.gameObject.tag == "Bullet"){
        health-=25;
    }
}

function Dead () {
    Destroy(gameObject);
    var posx = Random.Range(-50, 50);
    var posz = Random.Range(-50, 50);
    Instantiate(enemyl, Vector3(posx, 0.5, posz), transform.rotation);
}

Is there something I'm missing?

EDIT: The clone takes damage but doesn't die like the original when its health is <= 0.


texts: How to rotate libGDX particle to face the direction of movement

texts:
I'm creating spark particle effect so I created simple horizontal spark texture.

Here is what I currently have

If I change rotation property, I get this

But i want to rotate particle to face the direction of movement. How can I achieve it?

I use libGDX Particle Editor.


texts: unity : How to control the tile value of a material when extract material from imported game object (fbx, blend etc)

texts: I import .blend (or .fbx) file into unity and i extract the materials. Sometimes the rusult of the material tiling is 5x5  , sometime 1x1. What makes unity decide what tiling value to be used when extracting material ? Can we control it ? i'm confused because normally it's 1x1 but at some case the material has tiling of 5x5.


texts:
I was wondering if anyone would mind explaining a little about how a composition based spell system should work.

I've been working on this for a few days now, I think I understand the composite pattern enough for what I want to do as my entity's follow the same pattern.
(Everything has a single purpose)

But I am really having trouble connecting everything together.

For example my Entity has a Entity Caster Component and Entity SpellList Component and I believe following a pattern like this the Entity Caster Component shoudn't need to know anything about the spell other than it's just been asked to cast the one given, correct?

Which leads me to the problem of actually casting the spell as each spell is currently an empty object with 4 SpellComponents on it one of each type (SpellTargeting, SpellEffect, SpellLocomotion, SpellModifier) which all extend from SpellComp so I should in theory be able to treat them all the same.

But in practice I can't as targeting, modifier and effect mostly only need to run once where as locomotion needs to be called every frame.

I haven't figured out how to still call one inherited base method but have 1 component fire a coroutine and the others work as normal while still treating them the same.

Currently when I "cast" a spell I spawn an empty gameobject with the comps and enable the first component which does it's job and fires an event to start the next component until the last.

TargetComp > EffectComp (VFX) > LocomotionComp > ModifierComp (Heal/Hurt etc)

which has the obvious effect of leaving a empty object in my scene that responds to target input even after the spell is over.

I feel like at some point I've started mixing two separate systems together and made an unholy mess I no longer understand.

Every other part of the project has gone and is going fine but just thinking about taking another look at the spell system makes me lose a few brain cells.

I linked an empty project I created purely for testing this with my "oh god its so awful but it sort of works" implementation attempt.

I would add the code for each file but there is over 10 and most of them are just extending from a base abstract class so I can treat them the same and this post is already very long.

https://www.dropbox.com/s/ft6awn4v36a0pu0/Modular%20Spell%20Test.zip?dl=0

Any help appreciated, thanks!

Note: Also I use "Entity" as a base class for anything that moves and would have health, I am not trying to implement ECS, I think.. it was just the easiest way to categorize it in my head.


texts: How to automatically render all opaque meshes with a specific shader?

texts:
I have a specular outline shader that I want to be used on all opaque meshes of the scene whenever a specific camera renders. The shader is working properly when it is manually applied to some material. The shader is as follows:

Shader "Custom/Outline" {
Properties {
    _Color ("Main Color", Color) = (.5,.5,.5,1)
    _OutlineColor ("Outline Color", Color) = (1,0.5,0,1)
    _Outline ("Outline width", Range (0.0, 0.1)) = .05
    _SpecColor ("Specular Color", Color) = (0.5, 0.5, 0.5, 1)
    _Shininess ("Shininess", Range (0.03, 1)) = 0.078125
    _MainTex ("Base (RGB) Gloss (A)", 2D) = "white" {}
}

SubShader {
    Tags { "Queue"="Overlay" "RenderType"="Opaque" }
    Pass {
        Name "OUTLINE"
        Tags { "LightMode" = "Always" }

        Cull Off
        ZWrite Off
        // Uncomment to show outline always.
        //ZTest Always

        CGPROGRAM
        #pragma target 3.0
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
        };

        struct v2f
        {
            float4 pos : POSITION;
            float4 color : COLOR;
        };

        float _Outline;
        float4 _OutlineColor;

        v2f vert(appdata v) {
            // just make a copy of incoming vertex data but scaled according to normal direction
            v2f o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);

            float3 norm   = mul ((float3x3)UNITY_MATRIX_IT_MV, v.normal);
            float2 offset = TransformViewToProjection(norm.xy);

            o.pos.xy += offset * o.pos.z * _Outline;
            o.color = _OutlineColor;
            return o;
        }

        float4 frag(v2f fromVert) : COLOR {
            return fromVert.color;
        }
        ENDCG
    }
    UsePass "Specular/FORWARD"
}

FallBack "Specular"
}

The camera used fot the effect has just a script component which setups the shader replacement:

using UnityEngine;
using System.Collections;

public class DetectiveEffect : MonoBehaviour {

    public Shader EffectShader;

    // Use this for initialization
    void Start () {
        this.camera.SetReplacementShader(EffectShader, "RenderType=Opaque");
    }

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

    }
}

Unfortunately, whenever I use this camera I just see the background color. Any ideas?


texts: Stretching textures for CCSprites in Cocos2D

texts:
I'm making a game for iPhone and iPad w/ Cocos2D and Box2D.  I scale the size of square objects ("blocks") using a pixel-to-meters ratio depending on the particular device.  Can I stretch or shrink the textures and CCSprites as well?  I was considering having just one "blockImage.png" file and scaling it up/down depending on the device.

The alternative is having 2-3 sets of images for iPhone, iPhone 4, iPad etc.

Cheers!