texts: How do I implement an input wrapper like Unity's in SDL2?

texts:
This is my first time actually trying to wrap the the SDL event handling functions in a class of my own. I'm trying to achieve a design similar to unity's where you have this static Input class and you can call it's functions whenever to check for various input events.
Here is the class:
class InputManager
{
private:
    InputManager() = default;
    InputManager(const InputManager& c) = delete;

private:
    static SDL_Event event;
    static bool isKeyPressed;
    static bool isKeyReleased;
    static bool isMousePressed;
    static bool isMouseReleased;

    static int keyIndex;
    static int buttonIndex;

public:
    static InputManager* GetInstance();
    void Update();

public:
    bool KeyDown(int iKeyIndex);
    bool KeyStillDown(int iKeyIndex);
    bool KeyUp(int iKeyIndex);
    bool KeyStillUp(int iKeyIndex);
    bool MouseDown(int iButton);
    bool MouseStillDown(int iButton);
    bool MouseUp(int iButton);
    bool MouseStillUp(int iButton);
};

and it's implementations:
SDL_Event InputManager::event;
bool InputManager::isMousePressed = false;
bool InputManager::isMouseReleased = false;
bool InputManager::isKeyPressed = false;
bool InputManager::isKeyReleased = false;

InputManager* InputManager::GetInstance()
{
    static InputManager* instace = new InputManager();
    return instace;
}

void InputManager::Update()
{
    SDL_PollEvent(&event);
}

bool InputManager::KeyDown(int iKeyIndex)
{
    if(event.type == SDL_KEYDOWN && event.key.keysym.sym == iKeyIndex && isKeyPressed == false)
    {
        isKeyPressed = true;
        return true;
    }
    else if(event.type == SDL_KEYUP)
    {
        isKeyPressed = false;
        return false;
    }
    else
        return false;
}

bool InputManager::KeyStillDown(int iKeyIndex)
{
    if(event.type == SDL_KEYDOWN &&
       event.key.keysym.sym == iKeyIndex)
        return true;
    else
        return false;
}

bool InputManager::KeyUp(int iKeyIndex)
{
    if(event.type == SDL_KEYUP && event.key.keysym.sym == iKeyIndex && isKeyReleased == false)
    {
        isKeyReleased = true;
        return true;
    }
    else
    {
        isKeyReleased = false;
        return false;
    }
}

bool InputManager::KeyStillUp(int iKeyIndex)
{
    if(event.type == SDL_KEYUP &&
       event.key.keysym.sym == iKeyIndex && event.key.repeat == 0)
        return true;
    else
        return false;
}

bool InputManager::MouseDown(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONDOWN && event.button.button == iButton && isMousePressed == false)
    {
        isMousePressed = true;
        return true;
    }
    else if(event.type == SDL_MOUSEBUTTONUP)
    {
        isMousePressed = false;
        return false;
    }
    else
        return false;
}

bool InputManager::MouseStillDown(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONDOWN && event.button.button == iButton)
        return true;
    else
        return false;
}

bool InputManager::MouseUp(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONUP && event.button.button == iButton && isMouseReleased == false)
    {
        isMousePressed = true;
        return true;
    }
    else
    {
        isMousePressed = false;
        return false;
    }
}

bool InputManager::MouseStillUp(int iButton)
{
    if(event.type == SDL_MOUSEBUTTONUP && event.button.button == iButton)
        return true;
    else
        return false;
}

Now I know this class has it's flaws and it certainly does, for instance the KeyUp(int iKeyIndex) and MouseUp(int iButton) functions seem to always be true unless I move the mouse or do any type of event. I'm aware of issue and why it's happening but I can't seem to find a solution for it. I would like to know how to fix these issues.


texts: I made a set of 10 different "ocean" tiles, all interchangeable with one another, and I'd like to randomly attach these 10 different tiles together in different combinations over a large rectangular area -- what would be the best way to do so? I've thought of just adding each sprite into a script and then calling a for/foreach loop to add it into my world but that seems extremely expensive since I'd be adding over 1000 sprites. I don't want to reduce the number of sprites I have to add, I'm just seeing if there's a typical way people do this sort of thing.


texts: Getting points inside a circle with a given radius in a 2D array?

texts:
Let's say you have a system that removes everything within a square made up of 4 position points. This square is calculated by taking the center point and adding or subtracting the range from this center point seen here:
int xmin = x - range;
int ymin = y - range;
int xmax = x + range;
int ymax = y + range;

for (int i = xmin; i <= xmax; i++) {
     for (int j = ymin; j <= ymax; j++) {
          bounds[j, i] = 0;
     }
}

How would I change these bounds to be in a circular range instead of a square?


texts: Is tools programming experience useful for other positions?

texts: What does the possible career progression look like for a tools programmer? Would experience in that field be useful to gain other programming jobs in the industry, like gameplay, engine or AI programming? Or is it considered experience that only qualifies you for further tools programming jobs?


texts: Importing python DirectX into c++ DirectX program

texts:
I'm not asking for code or anything, just some advice on what to google, because I have no idea what to call this process.

I made a video player (with full controls) with python and DirectX and would like to just simply import the rendering of the display into a c++ DirectX fullscreen app. That way, it can be customizable to the user.  Any advice is greatly appreciated.


texts: How can I track a falling ball with a camera?

texts:
I have been trying to get my camera to follow a falling ball but with no success.

here is the code

        float cameraY = (FrustumHeight / 2)+((ball.getPosition().y) /2) - (FrustumHeight /2);
        if (cameraY <  FrustumHeight/2 )
            cameraY =  FrustumHeight/2;
        camera.position.set(0f,cameraY, 0f);
        Gdx.app.log("test",camera.position.toString());
        camera.update();
        camera.apply(Gdx.gl10);
        batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.draw(backgroundRegion, camera.position.x - FrustumWidth / 2,
 -cameraY - (FrustumHeight/2) , 320, 480);
        batch.draw(ballTexture, (camera.position.x - FrustumWidth / 2) + ball.getPosition().x,-cameraY + ball.getPosition().y - (FrustumHeight/2)  ,
                32, 32);

I'm sure I am doing this completely wrong - what is the correct way to do this?


texts: How should I implement a timer in a strategy game?

texts:
I'm developing a real strategy game for Android and want to implement timers. Those timers will represent the time remaining until some building is finished.

Say that i have a building in construction that takes 45 minutes to be completed.

How can I communicate this timer information between my client (Android app) my server and my database? Should I communicate to the server every second in which state my timer is?
Should I even do this on the server (i.e., should the timer run on the client)?

I'm inclined to assign this task to the server for security and integrity reasons, but i'm not sure on the way i can accomplish that.


texts: For Visual Studio Community 2017, 'Unreal Engine Installer' option is not available

texts:
On Visual Studio Community Installer, I cannot find 'Unreal Engine Installer' under 'Desktop Developemtn with C++' - 'Optional'. According to the tutorials I am learning, the 'Unreal Engine Installer' should be availbl.e

I have Visual Studio installed on 'C:' and Unreal installed on 'H:'; can this be the problem?


texts: How can I modify my procedural shadows to also show some of the walls?

texts:
I'm rendering shadows in Libgdx with the method from this tutorial. I think it's a nice and easy method.
I render all my shadows in a framebuffer, then invert it.

Before invert:

After Invert:

#ifdef GL_ES
#define LOWP lowp
precision mediump float;
#else
#define LOWP
#endif

varying vec2 vTexCoord0;
varying LOWP vec4 vColor;

uniform sampler2D u_texture;

void main(void) {
    vec4 diffuseColor = texture2D(u_texture, vTexCoord0);
    gl_FragColor = vec4(diffuseColor.rgb + vColor.rgb, vColor.a - diffuseColor.a);
}

That's all working fine.

Now I want to show a bit of the walls. But I'm not sure how. I tried using the
framebuffer with the lights, scale it a bit, and then draw the walls with blending.
But it's looking not very good:

Is there a better way?


texts:
would something like this be valid as an input to a vertex shader?

layout (location = 0) in float[6] faceTextureOffsets;

I know you can use things like vec3s but for this situation I need an array of 6 floats. I am using a texture atlas and I would like for different sides of the cubes i'm rendering to have different textures and I need a way to be able to change the position in the texture atlas.


texts:
I'm going over some SDL tutorials aimed at creating 2D games.

However, when I create a basic SDL program - is it hardware accelerated?

Or is hardware acceleration only relevant when it comes to 3D animations? Can a GPU help when it comes to pure 2D graphics?


texts: Which game logic should run when doing prediction for PNP state updates

texts:
We are writing a multiplayer game, where each game client (player) is responsible for sending state updates regarding its "owned" objects to other players.

Each message that arrives to other (remote) clients is processed as such:

Figure out when the message was sent.
Create a diff between NOW and that time.
Run game specific logic to bring the received state to "current" time.

I am wondering which sort of logic should execute as part of step #3 ?

Our game is composed of a physical update (position, speed, acceleration, etc) and many other components that can update an object's state and occur regularly (locally).

There's a trade off here - Getting the new state quickly or remaining "faithful" to the true state representation and executing the whole thing to predict the "true" state when receiving state updates from remote clients.

Which one is recommended to be used? and why?


texts: AudioSource not working. Empty Exception

texts:
I'm trying to load and play an wav file that exists in my Application.dataPath but when the game gets to the line _GoAudioSource.PlayOneShot(audioLoader.audioClip); It justs throws a empty exception and no sound is played.

I've already checked if the path is correct and it is. I've also tried uploading this wav file to an FTP and loading it via HTTP instead of File:/// but nothing changes.

This is my full code:

     private IEnumerator WriteResponseAudio(ResponseModel res)
     {
         File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME_RESPONSE), Convert.FromBase64String(res.intent.audio.content));
         string path = "file:///" + Application.dataPath + "/" + FILENAME_RESPONSE;
         WWW audioLoader = new WWW(path);
         yield return audioLoader;
         try
         {
             _GoAudioSource.PlayOneShot(audioLoader.audioClip);
         } catch (Exception ex)
         {
             Debug.LogError("Erro: " + ex.Message);
         }
     }

This is the version with HTTP request:

     private IEnumerator WriteResponseAudio(ResponseModel res)
     {
         File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME_RESPONSE), Convert.FromBase64String(res.intent.audio.content));
         string path = "http://www.raphaelrosa.com/response.wav";
         WWW audioLoader = new WWW(path);
         yield return audioLoader;
         try
         {
             _GoAudioSource.PlayOneShot(audioLoader.audioClip);
         } catch (Exception ex)
         {
             Debug.LogError("Erro: " + ex.Message);
         }
     }

This is the console:


texts: How can I reduce amount of graphics to draw for a smooth 2D character evolution transition?

texts:
I'm working on a game where the player has a character that can be fatter or skinnier, and maybe other transitions. Not only the height and width could change, but the complete appearance of the body.

I'm using separately the body parts for animations, and I can handle the animation transition pretty well.

I was thinking about drawing all the graphics to make nice and smooth transitions, but for example if the character has 20 states, and it has minimum 8 parts/state, I have to draw 160 graphics. It seems too much for me.

Is there a way to reduce the amount of work to have all of these states? I'm open to completely different techniques too.


texts:
I'm getting an error while build a tmx map using MonoGame Extended (see picture). By the looks of it, the importer can't find the tileset, which is weird.

In my Map.tmx file the source for the tileset is ../Tilesets/Tileset.png. The tileset is placed in a Tilesets folder in the content pipeline, and the map lies in a Maps folder, so it should work, but it doesn't? I get the same error if I place the Tileset.png in the same folder as Map.tmx and change source to just Tileset.png.

Any ideas what's causing this and how to fix it?


texts: Why is forward=down mouse orientation commonly called "inverted"?

texts:
If you look at 3D games that allow you to control the camera using the mouse--most notably first-person and third-person shooter style games--you'll usually find two specific details:

By default, pushing the mouse forward makes the camera look up, and pulling back looks down.
The option to reverse this (forward=down) is called "invert Y axis" or something similar.

I've never understood that, and it's always seemed backwards to me, to the point where I get wildly disoriented in any game with default settings on. It seems intuitively obvious that the mouse (or, even more so, a thumbstick, which even looks kind of like a head sitting atop a neck) is modeling the perspective character's head.  Move left, you look left. Move right, you look right. Push forward, the head pushes forward, and you look down... right?

In fact, this orientation was the default in a lot of early 3D games, such as flight simulators, MechWarrior 2, etc.  But at some point it changed, and people started calling the intuitive orientation "inverted" and disabling it by default.

Are there any historical reasons behind this reversal of the default camera control orientation?  Any articles, perhaps, on the rationale behind changing it, or studies showing why it was a desirable change to make?


texts: Create a trailing, ghosting effect of a sprite

texts:
I want to create a trailing, ghosting like effect of a sprite that's moving fast. Something very similar to this image of Sonic (apologies of bad quality, it's the only example I could find of the effect I'm looking to achieve)

However, I don't want to do this at the sprite sheet level, to avoid having to essentially double (or possibly quadruple) the amount of sprites in my atlas. It's also very labor intensive.

So is there any other way to achieve this effect? Possibly by some shader voodoo magic? I am using Unity and 2D Toolkit, if that helps.


texts: Obtaining vector representing local z axis orientation

texts:
I've been trying to get the vector that represents the local rigid body's true forward pointing (z axis, or blue colored) vector. I've been using Debug.DrawLine(...) to try and find out which position vector to use.

Debug.DrawLine(_rb.position, new Vector3(_rb.position.x, _rb.position.y, _rb.position.z + 10), Color.red, .01f, true);
Debug.DrawLine(_tf.position, new Vector3(_tf.position.x, _tf.position.y, _tf.position.z + 10), Color.green, .01f, true);

Debug.DrawLine(transform.forward, new Vector3(transform.forward.x, transform.forward.y, transform.forward.z + 10), Color.blue, .01f, true);
Debug.DrawLine(transform.forward, new Vector3(transform.forward.x, transform.forward.y, transform.forward.z + 10), Color.yellow, .01f, true);

rb.position and tf.position appear to be equivalent, while transform.forward and Vector3.forward are equivalent but are in the world's (x,y,z) 0 position. All four have the same orientation when I change the orientation of the Rigidbody via it's angular velocity property.

Why do you need the local z axis orientation?

I'm implementing a Vehicle in unity without using Wheel Colliers because they don't have the level of control that I want, and their physics are extremely wonky. Being able to obtain a vector representing the z axis orientation makes it very easy to turn the car, since I only have to modify the Rigidbody.angularVelocity function to get it to turn.

Code for reference

For reference, my driving controller code consists of three steps within the FixedUpdate() method.

First is the simple Turning algorithm, which creates a triangle relationship with the front and back wheel of the car and the requested steering angle and then factors this relationship into a rate of change of angular velocity:

if (Input.GetButton("Right")) {
  _steerAngle = 45;
  var l = Mathf.Abs(Vector2.Distance(new Vector2(BL.position.x, BL.position.z), new Vector2(FL.position.x, FL.position.z)));
  turningCircleRadius = l / Mathf.Sin(_steerAngle);
  _rb.angularVelocity = new Vector3(_rb.angularVelocity.x, new Vector2(_rb.velocity.x, _rb.velocity.z).magnitude / _turningCircleRadius, _rb.angularVelocity.z);
} else if (Input.GetButton("Left")) {
  steerAngle = -45;
  var l = Mathf.Abs(Vector2.Distance(new Vector2(BR.position.x, BR.position.z), new Vector2(FR.position.x, FR.position.z)));
  _turningCircleRadius = l / Mathf.Sin(_steerAngle);
  _rb.angularVelocity = new Vector3(_rb.angularVelocity.x, new Vector2(_rb.velocity.x, _rb.velocity.z).magnitude / _turningCircleRadius, _rb.angularVelocity.z);
} else {
  _steerAngle = 0;
  _rb.angularVelocity = new Vector3(0, 0, 0);
  _turningCircleRadius = 1 / 0f;
}

Then the force exerted by the engine is calculated and then converted into change in velocity:

var latSpeed = new Vector2(_rb.velocity.x, _rb.velocity.z).magnitude;
  if (Input.GetButton("Accelerate")) {
    var force = _rb.mass * 10;
    latSpeed += force / _rb.mass * Time.fixedDeltaTime;
  } else if (Input.GetButton("Brake")) {
    var force = -1 * 1000 * _rb.mass;
    latSpeed += force / _rb.mass * Time.fixedDeltaTime;
    if(latSpeed <= 0) latSpeed = 0;
  }

Finally, the velocity is modified:

_rb.velocity = new Vector3(transform.forward.x * latSpeed, _rb.velocity.y, transform.forward.z * latSpeed);

As you can see this driving algorithm would work fine on a completely flat surface, but would start to have wonky interactions with hills if the vehicle's pitch were to change.


texts: Colliders slightly intersecting each other; any solution?

texts:
Consider this simple scene:

In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider.

And the problem: if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height. The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam-- this only exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall.

This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist.

Is there a workaround? How can the box smoothly move across the floor without colliding with the seam?

Notes:

This does occur with capsule colliders but rare and is not very noticeable.
A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks.
This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity/position of the transform.


texts: Large amounts of strings to be used, but how to store them?

texts:
This is a question I've been meaning to ask. I have thought about it for a little bit and have a few ideas, but I'm not sure which is most secure, and will give me the most functionality with the most efficiency. For my game (being a story game) I have a plethora of strings that I'm going to need to display. I decided to split up the story into chapters, each chapter being a new scene(This way I could organize the content for the chapter). What I was thinking was that I could write regular text files with the chapter's content, while efficient and practical, this seems highly insecure. Then I thought, why not put it into large string arrays on a separate C# file. Well that's more secure, but it's not really practical and it has less efficiency. So I have found pretty much the two extremes here.

What would be the best way to deal with large amounts of strings in a secure, efficient, and functional way? Think about a happy medium compared to my two extremes.


texts: Unity2019 - PrintDocument ignoring 'DefaultPageSettings.Landscape = true'

texts:
So I'm trying to print from Unity in landscape and while I can get it to print just not in landscape.
So I create a PrinterSettings Object in 'void Start' and set the printer and tray from dropdowns... and that part appears to work but it's fully ignoring the Landscape property.
public void ShowDialog(string filePath, bool isLandscape)
{
    PdfiumViewer.PdfDocument pdfiumDoc = PdfiumViewer.PdfDocument.Load(filePath);
    _printDocument = pdfiumDoc.CreatePrintDocument();
    _printDocument.DocumentName = "Print Document";

    _isLandscape = isLandscape;

    _printPanel.SetActive(true);
}

public void Print()
{
    int index = _paperSourcesStrings.IndexOf(SelectedPaperSource);

    _printDocument.PrinterSettings = _printerSettings;
    _printDocument.DefaultPageSettings.Landscape = _isLandscape;

    if (index != -1)
    {
        _printDocument.DefaultPageSettings.PaperSource = _paperSources[index];
    }

    _printDocument.Print();

    _printPanel.SetActive(false);
}


texts: Simple networking, now that UNet is deprecated

texts:
I'm prototyping a two-player typing game in Unity. I don't have any experience making multiplayer games, so I'm not sure how to best approach the netcode.

For this game all I think I really need is an API for sending messages to and from a server - the two clients only care about what the other one is typing, and there isn't any gameplay that's even remotely related to physics. Looking into UNet, it seems like the parts based on synchronizing game objects do more than my game needs, but the messaging stuff from the HLAPI seems like a good fit. That said, this is a real time game, so low latency is ultimately more important than any API style considerations.

The wrench, however, is that Unity is deprecating UNet without shipping any replacements. I'd start working with HLAPI, but I don't want to have to replace all of the networking code down the line or even have to shut down the game when Unity's servers go down, if that's what will happen after using HLAPI.

So as a beginner to multiplayer development, with relatively low API requirements, where do I go when Unity multiplayer is in flux? Should I learn the DOTS-Netcode mentioned in this recent blog post? Should I go with a third party solution like Photon? Or will the HLAPI be sufficient, even post-deprecation?


texts: LibGDX game crash without errors (maybe AssetManager)

texts:
i have a problem with my game. It's a endless run shooter/platform made with LibGDX (Scene2d and box2D).

I do tests with LG G2, LG G3, Galaxy s4, desktop and android emulator and i have no one problem, but when i try to start my game on Galaxy s3 i have a very strange problem.
The game crashes with no error in android and no error in android studio, simply crashes... i think its very strange because i'm developing it since a year and i always got wich error makes it crashes.

I think it's AssetManager fault because crashes often happens during loading or just finished loading (sometimes after 20-30 seconds of playing), so i tried to load less stuff and its work. I added one piece per time and at a certain point i always got a crash.
In total my assets are 11mb... not so much i think.
The biggest asset is the background, 2 pieces 1920*1080, near 2*70kb (yes, 70kb)...

i have in Android Studio monitor, cpu use 10~20% kernel and 10~20%user and 10~12mb memory

Here it is where the crash happens, i hope to solve soon... Thanks guys!

   public class ScreenSwitcher extends Game {
   private static ScreenSwitcher instance = null;

   public static AssetManager manager  = new AssetManager();

   private ScreenSwitcher(){
   }

@Override
   public void create () {
        loadTitle();
   }

   public static ScreenSwitcher getInstance(){
      if(istanza==null)
         istanza = new ScreenSwitcher();

      return istanza;
   }

   public void loadTitle(){
      manager.load("atlas/splash.png", Texture.class);
      manager.load("atlas/mainTitle.atlas", TextureAtlas.class);
      manager.load("atlas/shop.atlas", TextureAtlas.class);
      manager.load("atlas/loading.atlas", TextureAtlas.class);
      manager.load("atlas/duro.atlas", TextureAtlas.class);
      manager.load("atlas/sfondo.atlas", TextureAtlas.class);
      manager.load("atlas/nuovoRoy.atlas", TextureAtlas.class);
      manager.load("atlas/altro.atlas", TextureAtlas.class);
      manager.load("atlas/shipFlag.atlas", TextureAtlas.class);
      manager.load("atlas/collezionabili.atlas", TextureAtlas.class);
      manager.load("atlas/lucertole.atlas", TextureAtlas.class);
      manager.load("atlas/lumaca.atlas", TextureAtlas.class);
      manager.load("atlas/terreni.atlas", TextureAtlas.class);
      manager.load("atlas/decorazione.atlas", TextureAtlas.class);
      manager.load("atlas/piatte.atlas", TextureAtlas.class);
      manager.load("atlas/nuvolette.atlas", TextureAtlas.class);
      manager.load("atlas/pezzi.atlas", TextureAtlas.class);
      manager.load("atlas/pulsanti.atlas", TextureAtlas.class);
      manager.load("atlas/ragnetto.atlas", TextureAtlas.class);
      manager.load("atlas/scatole.atlas", TextureAtlas.class);
      manager.load("atlas/volante.atlas", TextureAtlas.class);
      manager.load("atlas/volanteBonus.atlas", TextureAtlas.class);
      manager.load("atlas/volantePorta.atlas", TextureAtlas.class);
      manager.load("atlas/trappole.atlas", TextureAtlas.class);
      manager.load("atlas/esplosione.atlas", TextureAtlas.class);
      manager.load("atlas/jumpfall.atlas", TextureAtlas.class);
      manager.finishLoading();

      setScreen(new GameScreen());
   }


texts: What's the best way to draw gizmos in build

texts:
I currently use Unity gizmos for many debugging purposes, but I'd like almost all of them to be visible to the player in-game (when the game is built).
For example, when a player is dragging to place a wall along a grid, I use Gizmos.DrawCube.
I know of a couple of options:

ALINE - an asset on Unity asset store, but currently doesn't work with 2D Experimental URP
Line renderer - seems very manual and tedious to do, and I'm unsure how I could modify it using code
Placing pictures as UI elements over selected tiles (seems pretty expensive to do?)

Any suggestions are appreciated!


texts: Unity - How to change editor play/stop button positions for dual monitor layout

texts: Is it possible to change the play/stop buttons positions in editor? I am trying to make a layout for Dual-Screen, however the buttons are right in the middle of the two screen. So, it makes it hard to click the buttons.


texts: Unity - are particles rendered and calculated when off-screen?

texts: I have a scene where I have a lot of instances of the same particle system. As the game will go for mobile, I fear the particles are calculated even when they are not shown. So to cut it short, I would like to know if the particle system is being calculated and rendered even if off-screen.


texts: Get the game state using Multithreading in Java Monkey Engine 3

texts:
I’ve been trying out Java Monkey’s multi threading recently via the wiki’s tutorial. Since I just wanted to test a prototype clinet, I made a program which creates some cubes using the ‘Cubes’ library (hub.jmonkeyengine.org/wiki/doku.php/jme3:contributions:cubes), and then serializes it to some byte data (which is what the server would do to the map chunks near a player). The aim is to imitate a chunk being sent from the server, which would occur in a separate thread, as mentioned in the networking tutorial on the wiki (hub.jmonkeyengine.org/wiki/doku.php/jme3:advanced:networking).

Each chunk would have it’s own node to store it, and the chunk would be replaced if the server sent either an update of the chunk, or if the player moved into a new region (which would cause the chunk to be replaced). The code is here. The issue is though, is that I need to recreate an empty chunk before I can read from the bytes, which requires collecting the application settings. As well as this, I cannot modify the game scene within a separate thread (which the function does). The code below is from line 93+.

//...
//(In Update Loop)
if (future.isDone()) {
    //Binds the temporary data to the clone object
    blockTerrainClone = (BlockTerrainControl) future.get();
    future = null;
//...

Callable<BlockTerrainControl> serverInput = new Callable<BlockTerrainControl>() {
    public BlockTerrainControl call() {
        /*Creates a temporary data storage object, then assigns the data.
        I can't mutate the current BlockTerrainControl which is being rendered,
        as this is a seperate thread.*/
        BlockTerrainControl data = new BlockTerrainControl(CubesTestAssets.getSettings(app), new Vector3f());
        CubesSerializer.readFromBytes(data, serializedBlockTerrain);

        //Returns the data
        return data;
    }
};

The multithreading wiki article (near the bottom) does partially cover how to modify the scene and get access to the game state, but not into much detail. Would anyone be able to expand on that section, and explain how I may be able to transfer the blocks from the server to the client in a separate thread (or in this case, make the data transfer from one thread to another)?

If I missed out anything in the question, I'd be happy to add it!


texts:
I'm planning on how my multiplayer game client game loop should work. While I'm convinced that server should be moved from game loop into it's own thread, I'm not sure what should I do about receiving server data. To me most logical approach would be something like this:

protected override void Update(GameTime gameTime)
    {
        receiveServerData(); //may receiving data lag the game?
        updateWorld();
        processInput();
        sendClientMovementToServer();
    }

private void receiveServerData()
    {
        NetIncomingMessage msg;
        while ((msg = netClient.ReadMessage()) != null)
        {
            // ...
        }
    }

But I'm afraid that reading incoming data inside game loop can lag the game if processing too much data, so here's my question: Is it good idea to process incoming server data inside game loop, or should create thread for receiving this data instead? And if so, how should I do it?


texts: Calling functions that needs to be on update()

texts:
So I have a function DialogueRun() for a Dialogue System that changes the line on the dialogue box whenever you click. Which means it has to be in Update(). My test works so far but my next problem is how to make the whole dialogue box only appear whenever I click on a character.
I tried making the characters as buttons and it does make the dialogue box show up whenever clicked, but it won't change the dialogue lines because that function has to be in an update method.
I'm looking at OnMouseDown() right now but the result will be probably the same. Any ideas?
 public void DialogueRun()
{
    dialogueBox.SetActive(true);
    dialogue.text = textLine[nextLine];

    if (nextLine < textLine.Length - 1)
    {

        if (Input.GetKeyDown(KeyCode.Mouse0))
        {

            nextLine += 1;
        }
    }
    else
    {            //counter++;
        dialogueBox.SetActive(false);
        return;
    }


texts: Unity FPS Offline Multiplayer (MultiLan) Player Animation

texts:
I am creating an FPS game in local multiplayer. One player creates the hot-spot game, and the other one connects through WiFi network and plays the game. And i am doing this using unity MultiLan Package available in Unity Assets Store.

when the player connect to the Game i play the player animation like walk , jump etc. But the problem is animation can play only which player who host the Game, not play to other player who join the Game in host network.

That is Player Script.

private MNetwork networkSrc;
public Btn_Jump jumpScript;
public Btn_DPad Btn_DpadScript;

void Awake() {
    if (GetComponent<NetworkView>().isMine) {
        trans = transform;
        contr = trans.GetComponent<CharacterController>();

        if (jumpScript == null) {
            jumpScript = GameObject.Find ("3 Jump").GetComponent<Btn_Jump> ();
        }
        if (Btn_DpadScript == null) {
            Btn_DpadScript = GameObject.Find ("6 D-Pad").GetComponent<Btn_DPad> ();
        }
    }
}

void Start() {
    if (GetComponent<NetworkView>().isMine) {

        // If it's my player : search the networkManager component
        networkSrc = GameObject.Find("MNetwork").GetComponent<MNetwork>();
        PlayerAnimatorComponent = GameObject.Find ("Swat").GetComponent<Animator> ();

        FPS_Events.ChangeCharacterMotor(motor);
    }

}
 void Update() {

    if (!networkSrc.isPlayerExitGame) {

            if (currentMotor == null)
                FPS_Events.ChangeCharacterMotor (motor);
            try {

                currentMotor.Update ();
            } catch {
            }

            if (jumpScript.Player_jump) {

            }
            if (Btn_DpadScript.Player_Run) {
                RunAnimation ();
            }

    }
}

void RunAnimation(){
    GetComponent<NetworkView> ().RPC ("SyncAnimation", RPCMode.All);
}

[RPC]
void SyncAnimation(){
    if (Btn_DpadScript.Player_Run) {
        PlayerAnimatorComponent.SetFloat ("Walk",2f,0.1f,Time.deltaTime);

    }
}

In this Script there is "Btn_DpadScript" object of Virtual joystick Script name is "Btn_DPad" for Player Movement.

When player move then "Player_Run" Boolean variable is true and play the Walk animation of player in SyncAnimation() method.

But it is stuck to play animation in all player in same network.

Any one can know how to play animation in all network player using MultiLan Package then tell me. I can't found in Google Search about player Animation in network using MultiLan Package.

what should i do don't know any one can suggestion then i really appreciate thank you.


texts:
What is the best way to handle the intro, title screen, and menus? I am contemplating that each of these could be a "scene" object of sorts. Perhaps in the game loop based on what needs to be done, a specific scene is loaded and everything that is contained within is executed. When that scene is no longer needed, it is unloaded.

Am I thinking about this correctly? I am not sure if "Scene" would be the best term to use in this case, but it is the best way I can describe it. Perhaps screen objects handled by a screen manager? If there is something more appropriate, I would love to know!

Also, for example I am thinking to have:

Intro "scene"
Main menu
Settings


texts: Logic level representation that distinguishes "> and > the bridge"

texts:
I have an logic level/map representation for a 3D game that uses vector<Area> where:

class Area{
    vector<Point2D> bounding; //determines the shape of the Area, its borders
    //bounding of Area is like borders of country
    //(it's easy to test if something is inside area)

    vector<Obstacle> obstacles; //general type for all static objects inside this Area
    //each Obstacle has boundingBox (center, halfSize, rotation)

    vector<Dynamic> dynamicObjects; //same as obstacles, but the use of separated vector
    //for dynamic objects helps with few things

    Player * player = 0; //like Obstacle, but it has special treatment

    vector<Area*> connectedAreas; //I won't went deeper into how Areas are connected.
    //For simplify, let's assume we are working on one Area.
    //Or that when Player leaves Area, all connectedAreas start a test if he entered
    //one of them (it's not the case, but work fine for purposes of that example).
    ...
};

It's quite simple and very low memory-consuming representation for large areas (grid representation would grow and grow with the size of area). I also find it quite good when it comes to some AI algorithms that my game uses. I don't have too advanced collisions in my game (so I don't need to care about them in the level representation). So generally, I'm happy with that representation.

Still, I have one problem: sometimes some parts of the map have "height-levels" - e.g. bridge: you can be either under the bridge or above it (and you can go above only from certain fragments of map). How can I represent that?

For caves or multi-floor buildings I can just use vector<Area> instead of single Area/Area's fragment. That vector<Area> could hold separated Area for each floor.

But when the mesh has kind of "smooth" transitions between levels (bridges, some parts of mountains and any non-separable fragments of map) - it doesn't looks like good solution anymore.

For example, here player is able to go either under the tree or above the trunk:

P.s. I am not asking for the graphic representation. I've separated the game logic and graphic engine as much as possible. The 3D engine uses triangles of course, with much more details then game logic need or want (less data => faster processing).


texts: OpenGL GL_LINE_STRIP produces arcs with visible line edges

texts:
Another member mentioned an issue while drawing arcs with GL_LINE_STRIP.
He has GL_LINE_SMOOTH enabled.

The question is, how could he avoid the tiny gaps between vertices without increasing their number?

Edit: The original discussion was on SO. Click here for more info.


texts: Real hardware acceleration of vector images?

texts:
Basically vector graphics have many advantages, especially that they scale very nicely.
So there are many reasons to use them in 3D and 2D games.
Is there any support for hardware accelerated vector graphics?

I know it's possible to parse SVGs and generate filled vertex buffers, but that has many disadvantages over e.g. parsing SVG into a small binary format and let the GPU handle it.
Of course the GPU would need to support most non-trivial SVG objects like paths, gradients and patterns to be actually usable.


texts:
I am making a game targeted towards mobile, so I am experimenting around to know how I can boost performance.

Now I have a rectangle with a road texture on it. This I made in Blender. And as expected it has 2 tris.

I made a c# script to add these rectangles together to make a long road. So if I make a road 100 unit long, I have 100 such rectangles, and I expect that their total tris count becomes 200.

Now while running the game, Stats panel shows 8.2k tris for entire scene. And when I disable this 100 unit long road, Stats shows 7.8k tris. So why are there 400 tris for 100 rects?

For each rectangle object, I have already turned off the "cast shadows" property.

Link to blend file https://drive.google.com/file/d/0BztX2HefTk_wb1VuSUlONXVxaE0/view?usp=sharing

Link to texture file https://drive.google.com/file/d/0BztX2HefTk_wc3JvdTBJZmphRUU/view?usp=sharing

EDIT (adding code for builder script)

void createRoad() {
    Vector3 rotation = new Vector3(270, 0, 0);

    float z_size; // Value assigned in CreateWizard()
    Object road_item; // Assigned in CreateWizard()

    for (int i = 0; i < count; i++) {
        GameObject roadPiece = (GameObject)Instantiate (road_item);
        roadPiece.transform.parent = ((GameObject)Selection.objects[0]).transform;
        roadPiece.transform.localPosition = new Vector3 (0, 0, i * z_size);

        roadPiece.transform.localEulerAngles = rotation;
        roadPiece.name = BASE_NAME + (i+1);

        //Turn Off cast-shadows
        roadPiece.GetComponent<MeshRenderer>().shadowCastingMode =
            UnityEngine.Rendering.ShadowCastingMode.Off;
    }
}


texts: Load Texture From Image Content In Runtime

texts:
Basically I wrote a world editor for a game I'm working on. Looking ahead, I was brainstorming ways to save the created world including the tile-sets (this game will rely on a tile engine).

I was hoping to save the image data of each tile-set in the same file containing the tile positions, etc. and load the image data into a Texture with XNA.

Is it possible? Something like this is what I'm going for.

Texture2D tileset = Content.LoadFromString<Texture2D>("png tileset data");


texts:
In the antique game spy vs. spy, two players play on a single computer. The screen is split, with each half showing the viewpoint of one player.

Is it possible to create such an effect in Unity? The main problem is that Camera.main is a global variable, so it is not clear how to have two cameras.


texts: How can I procedurally find a wall that separates two or more points on a grid-based map?

texts:
I'm trying to generate walls that cut off a given point from other given points. The attached image shows the sort of thing I'm after:

Blue separated from Red.
Blue separated from Red and Yellow.
Blue separated from Red with tile obstructions.
Multiple Blue separated from multiple Red.

Any ideas how to do this?


texts: XNA 4.0 - Normal mapping shader - strange texture artifacts

texts:
I recently started using custom shader. Shader can do diffuse and specular lighting and normal mapping. But normal mapping is causing really ugly artifacts (some sort of pixeling noise) for textures in greater distance.

It looks like this:

This is HLSL code:

// Matrix
float4x4 World : World;
float4x4 View : View;
float4x4 Projection : Projection;

//Textury
texture2D ColorMap;
sampler2D ColorMapSampler = sampler_state
{
    Texture = <ColorMap>;
    MinFilter = Anisotropic;
    MagFilter = Linear;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

texture2D NormalMap;
sampler2D NormalMapSampler = sampler_state
{
    Texture = <NormalMap>;
    MinFilter = Anisotropic;
    MagFilter = Linear;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

// Light
float4 AmbientColor : Color;
float AmbientIntensity;

float3 DiffuseDirection : LightPosition;
float4 DiffuseColor : Color;
float DiffuseIntensity;

float4 SpecularColor : Color;
float3 CameraPosition : CameraPosition;
float Shininess;

// The input for the VertexShader
struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
    float3 Normal : NORMAL0;
    float3 Binormal : BINORMAL0;
    float3 Tangent : TANGENT0;
};

// The output from the vertex shader, used for later processing
struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
    float3 View : TEXCOORD1;
    float3x3 WorldToTangentSpace : TEXCOORD2;
};

// The VertexShader.
VertexShaderOutput VertexShaderFunction(VertexShaderInput input, float3 Normal : NORMAL)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    output.TexCoord = input.TexCoord;

    output.WorldToTangentSpace[0] = mul(normalize(input.Tangent), World);
    output.WorldToTangentSpace[1] = mul(normalize(input.Binormal), World);
    output.WorldToTangentSpace[2] = mul(normalize(input.Normal), World);

    output.View = normalize(float4(CameraPosition,1.0) - worldPosition);
    return output;
}
// The Pixel Shader
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 color = tex2D(ColorMapSampler, input.TexCoord);

    float3 normalMap = 2.0 *(tex2D(NormalMapSampler, input.TexCoord)) - 1.0;
    normalMap = normalize(mul(normalMap, input.WorldToTangentSpace));
    float4 normal = float4(normalMap,1.0);

    float4 diffuse = saturate(dot(-DiffuseDirection,normal));
    float4 reflect = normalize(2*diffuse*normal-float4(DiffuseDirection,1.0));
    float4 specular = pow(saturate(dot(reflect,input.View)), Shininess);

    return  color * AmbientColor * AmbientIntensity +
            color * DiffuseIntensity * DiffuseColor * diffuse +
            color * SpecularColor * specular;
}

// Techniques
technique Lighting
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

Any advice? Thanks!


texts: Engine for 2.5D Voxel Based City Simulation

texts:
We're looking into making a game where you're part of a city and you're interacting with its economy and people. The world should be an open and procedurally generated sandbox to enable players to the most freedom they can get.

The question we're unable to answer is whether to use a game engine and if yes, which one. We don't have any experience with engines as we're from a web development background.

The style is planned to be similar to Kingdoms and Castles:

low poly
voxel based
more or less 2.5D as in you're looking down on the world

We have been thinking about Unity and Unreal and are wondering whether those engines are "overkill" or whether they are able to compile down to a result where the unnecessary parts aren't in the game anymore. Also we've been thinking about a HTML5 / JavaScript basis. Obviously, it has immense platform benefits, but we're not sure whether performance would be adequate.

tl;dr to not get this lost in discussion: What are the benefits and drawbacks of

the usual 3D game engines like unity and unreal
a web based approach
a completely new engine (would the extra effort be justifiable?)

Thanks for any advice


texts: Sharp DX Identity Matrix, Matrix.Forward vector pointing at negative Z

texts: I'm trying to take a steady grip on Sharp DX. Already done some work like translating, scaling and rotating objects. Now i have to calculate the rotation matrix using only direction vector and arbitrary UP vector which is Unit Y vector (0,1,0). And this is where everything I know about Direct X graphics falls apart: I filled the Matrix.Forward with the normalized DIRECTION vector, and then crossed it with arbitrary UP (exactly this: DIR cross UP, not the other way), the resulting vector put in Matrix.Right property. Now if I put (0,1,0) in the Matrix.Up property, my model is facing the exact opposite direction to the expected direction (it faces backwards). Further investigation brought me to the fact that the Matrix.Identity matrix faces the NEGATIVE Z direction, which is weird to me as I thought that Identity would face positive X,Y,Z axes. Now I can overcome my problems by flipping any of the axes, but this clearly is not comforting to me, as there is something i must have missed in the meantime. So the ultimate question is: Why my Identity matrix points positive Y axis (good), positive X axis (nice, i expect this) and NEGATIVE Z (help!)


texts: How to create UI with multiple panels for multiple resolutions

texts:
I am trying to create scene that has multiple panels, but only one is visible. When user clicks on appropriate button a transition is happening: camera moves to the right revealing panel on the right or it moves down revealing panel that is down.

My first attempt was to have some C# script/controller that will change position of all three panels at the same time using Vector.lerp, however, problem that I see is multiple resolution. If I have resolution other than 480x800, panels overlap and I can't make transitions right (for example, to move right I move all three panels on the x-axis by -480).

How would I do this?


texts: Checking 2 instances of the same object in GameMaker

texts:
There are 2 blocks.
If the player stands on a block, some sound should loop and when he gets off it should stop.

Problem is,
The game checks both the objects and when player is on 1 block, obviously he is not on other, so checking this it stops the sound, never letting it play(sound).

if place_meeting(x, y-1, obj_player)
{
   if !audio_is_playing(snd_cart)
        {
             audio_play_sound(snd_cart, 10, true);
        }
}
else
    {
        audio_stop_sound(snd_cart)
    }

This is the code please help me on this


texts: Changing Ogre3D terrain lighting in real time

texts:
I'm looking at the Ogre 3D library and I'm browsing through some examples / tutorials. My question is about terrain. There are a few examples showing how great the terrain system is, but I think that the global illumination and shadows of the terrain have to be pre-computed, which kinda makes it impossible to integrate this with a day / night cycle.

Is there a way to change the terrain light sources in real time? If so it is possible to do it and keep a decent FPS?


texts: How to make a list containing both strings and functions in c#?

texts:
Whilst it doesn't neccesarily need to be a list, I just need a variable that I can index, and arrive at either a string or a function. I've tried using List and whilst this works for strings, when I try to store a function I get an error message along the lines of "cannot convert from void to object".

Does anyone know how this might be done?


texts:
What I'm attempting to do is create a game in which a space ship explores a large area of space.  I'm randomly generating placement of planets, space stations etc.  I want to use the ParallaxBackground (I actually had to find a custom implementation which supports both x and y parallax values).

When a planet is generated I create a sprite, and add a new parallax entity to the background.

My issue is that when I place the sprite, it is not being placed properly (due to the parallax calculation I'm assuming).  As the player navigates further away from the origin (0,0 in world space), the offset from the position the object is supposed to appear in the background and the position in which it actually appears gets larger and larger.

Here is the code for the custom drawing of the ParallaxEntity2D:

public void onDraw(final GLState pGLState, final Camera pCamera, final float pParallaxValueX, final float pParallaxValueY) {
            pGLState.pushModelViewGLMatrix();
            {
                final float cameraWidth = pCamera.getWidth();
                final float cameraHeight = pCamera.getHeight();
                final float shapeWidthScaled = this.mAreaShape.getWidthScaled();
                final float shapeHeightScaled = this.mAreaShape.getHeightScaled();

                //reposition
                float baseOffsetX = (pParallaxValueX * this.mParallaxFactor);
                if (this.mRepeatX) {
                    baseOffsetX = baseOffsetX % shapeWidthScaled;
                    while(baseOffsetX > 0) {
                        baseOffsetX -= shapeWidthScaled;
                    }
                }

                float baseOffsetY = (pParallaxValueY * this.mParallaxFactor);

                if (this.mRepeatY) {
                    baseOffsetY = baseOffsetY % shapeHeightScaled;
                    while(baseOffsetY > 0) {
                        baseOffsetY -= shapeHeightScaled;
                    }
                }

                //draw
                pGLState.translateModelViewGLMatrixf(baseOffsetX, baseOffsetY, 0);

                float currentMaxX = baseOffsetX;
                float currentMaxY = baseOffsetY;

                do {
                    this.mAreaShape.onDraw(pGLState, pCamera);

                    if (this.mRepeatY) {
                        currentMaxY = baseOffsetY;
                        do {
                            pGLState.translateModelViewGLMatrixf(0, shapeHeightScaled, 0);
                            currentMaxY += shapeHeightScaled;
                            this.mAreaShape.onDraw(pGLState, pCamera);
                        } while(currentMaxY < cameraHeight);
                        pGLState.translateModelViewGLMatrixf(0, -currentMaxY + baseOffsetY, 0);
                    }
                    pGLState.translateModelViewGLMatrixf(shapeWidthScaled, 0, 0);
                    currentMaxX += shapeWidthScaled;
                } while (this.mRepeatX && currentMaxX < cameraWidth);
            }
            pGLState.popModelViewGLMatrix();
        }

This is far beyond my ability to understand in terms of the calculation required to figure out where in screen space the sprite needs to be placed for it to show up in the background properly.  I've gotten close by hacking together some simple math, but I want this to be perfect.

I guess first I need to understand what the above onDraw code is doing exactly.  Maybe there is another approach that would work better for this instance?  I explored being able to use the z component on a sprite, but I couldn't get this to work with GLES2 (the example for GLES1 is here).


texts:
I'm developing on D3D11 and D3D12 in parallel. D3D12 is really difficult, but I learn it gradually. I faced a problem such as passing an array of textures to a vertex Shader. The method Textures2DArray was interesting in D3D11 , but it had disadvantages (size of texture, width and height must be the same, the same levels of MipMaps etc). As a result: I'm looking for a way to transfer a dimensionless ( if it is possible ) texture array, or at least an array of fixed size, but with different textures (*.dds (mipmaps, *.jpg etc). Why is it so necessary? Let's imagine that a model has been loaded. It has 50 textures. I loaded all 50 textures on the CPU, built an array from it, created the necessary descriptors and sent it to the Shader. I get the right texture in the Shader using the index. Thus, there will be one call to the GPU, instead of multiple calls = = number of textures in the model. Thank you for any information.

P.S.: I know about texture atlases, but in ordinary geometry I do not see any benefit from it


texts: Intentionally using "worse machines" to develop a game?

texts:
I am developing a game intended for desktop computers.
I am afraid of developing a game that will be too costly in aspects of performance, so I am wary of using a machine that might be better than the target devices.
However, I don't know yet what the target devices will look like when my game is finished in 5 years.
How do Indy developers choose a device for developing their game in order not to get carried away with its performance?
Just an example to make it more clear:
If a developer had access to a quantum computer, I guess they shouldn't use it. Else they would lose their ability to estimate the performance on the target devices.
Or is the "developer machine selection approach" not how it's done, and instead, there is simply a certain tri count limit for everything? (I remember that for RE4, there was simply a hard limit for tri count for meshes)


texts: Unity Pre Build Script - Add target dependent UI Elements

texts:
I wrote a postbuild script that deploys my builds to google drive. That works great, but when I tried to use the same type of logic on a pre build script, it fails. I'm trying to enable all game objects with the tag Mobile if the platform is mobile (andriod or ios). Otherwise turn those off. This is what I have for a script:

#if UNITY_EDITOR
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using UnityEditor;

public class PreBuild : IPreprocessBuildWithReport
{
    public int callbackOrder => 0;

    public void OnPreprocessBuild(BuildReport report)
    {
        var mobileGameObjects = GameObject.FindGameObjectsWithTag("Mobile");
        switch (report.summary.platform) // todo: make sure all targets are populated here
        {
            // mobiles
            case BuildTarget.Android:
            case BuildTarget.iOS:
                //enable all game objects
                foreach (var mobileGameObject in mobileGameObjects)
                {
                    mobileGameObject.SetActive(true);
                }

                break;
            // standalones (desktops)
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneLinux64:
            case BuildTarget.StandaloneOSX:
                foreach (var mobileGameObject in mobileGameObjects)
                {
                    mobileGameObject.SetActive(false);
                }

                break;
            // todo: consoles
        }
    }
}
#endif

The build runs fine, but when I run in mobile, none of the UI elements are there (off by default). Here is the heirarchy of them in my project:
 (screenshot not working):

- UI (Canvas Game Object)
  - Mobile ("Empty" Game Object, is tagged with "Mobile")
    - Joystick1
    - Joystick2
    - ActionButton

What am I missing?


texts: How to find the smallest distance between two 4-sided objects in 3D space?

texts:
I was wondering if there is a way to calculate the smallest distance between two 4-sided objects in space. In this specific scenario, the only information I know about both of them are the 4 points that make up their vertices (so 8 points in total). Is there a way to achieve this?

Also, I'm considering that both shapes have a non-zero volume and that they do not intersect each other.


texts: Having two points (line) how can I substract a specific amount to each point?

texts:
I have two points that make a line. And I need to subtract a specific amount to each point keeping the direction of the line. I know the radius which is the amount to subtract.

The red dots of the first line is what I have, and the dots of the second line is an example of what I would like to calc.


texts:
I've been programming a multiplayer game and its coming together very nicely. It uses both TCP and UDP (UDP for movement and TCP for just about everything else). What I was wondering was how I would go about sending multiple moving AI without much lag. At first I used TCP for everything and it was very slow when people moved. I'm currently using a butchered version of this http://corvstudios.com/tutorials/udpMultiplayer.php for my movement system and I'm wondering what the best method of sending AI movements is.
By movements I mean the AI chooses left/right/up/down and the player can see this happening.

Thanks.


texts: Where should I put the SDL_Renderer* using the ECS with SDL2 and C++?

texts:
So I'm still learning about ECS (Entity Component System) and whenever I'm thinking about the architecture and actual implementation, I just can't figure out where should I put the SDL_Renderer*.

So far what I've learned is that the Entity class should have its own unique ID, there should be a Component and System class and things like RenderComponent and RenderSystem should be derived from them. RenderComponent should contain all the data and the RenderSystem should contain the actual algorithms (correct me if I'm wrong so far).

I'm using C++ and SDL2 and I don't know how about you guys but I never really used more than one SDL_Renderer and I'm not intending to do so either. I always just create a renderer for the window and copy everything to that one renderer and than I present that renderer to the screen.
So my questions are:

In an ECS design like I explained above, where should I put my
SDL_Renderer?
What should the RenderComponent, and RenderSystem,    contain?


texts: Integrating Bullet3 into a C++ project - Linking to libraries

texts:
I've been following the BulletQuickstart guide and I get as far as generating the vs2010 solution and converting to newer. I've also been following this very good answer from a few years ago and have included the src folder into my project.

The only thing that remains is to link the libraries after building the bullet solution but I'm not entirely sure which ones are the correct ones to use. I've tried:

Linking against Bullet3Collision.lib, Bullet3Dynamics.lib and LinearMath.lib
Linking against BulletCollision.lib, BulletDynamics.lib and LinearMath.lib
Same as the above options, but with original filenames i.e. BulletCollision_vs2010_debug etc.

In every instance I get the usual errors when not linking properly:

 unresolved external symbol "void * __cdecl btAlignedAllocInternal.......

I have already checked the Additional Library Directories and Additional Dependencies

The small code I have calling some bullet stuff is:

#pragma once

#include "btBulletDynamicsCommon.h"
#include <stdio.h>

class BTPhysics
{
public:
    BTPhysics();
    ~BTPhysics();

    void Init();

private:
    btDefaultCollisionConfiguration* m_pCollisionConfiguration;
    btCollisionDispatcher* m_pDispatcher;
    btBroadphaseInterface* m_pOverlappingPairCache;
    btSequentialImpulseConstraintSolver* m_pSolver;
    btDiscreteDynamicsWorld* m_pDynamicsWorld;
};

Am I supposed to grab the library files from somewhere else other than the bin directory after building the bullet3 solution?


texts: Unity "Update" method with lots of objects with logic

texts:
In my game I'm working on in Unity, I want to have energy and machines (i.e ore processing machines, smelting (think Minecraft modded)), but I was thinking about performance.  The player could have quite a few of these machines in their base, all of them could be doing something and could be off screen, so this could effect performance as each machine will have logic to handle whatever it needs to do, and lots of them could be running at the same time.

Machine example;  Let's say we have a machine that crushes stone.  Player puts it into the machine slot, machine then starts crushing it if it has enough energy, and after X seconds, it outputs the crushed stone.  Player could keep the machine UI open and watch the progress (i.e progress bar), or be far away from it.

Should these machines be running constantly in Update, if not, what would be a better way to do this?


texts: How to convert RotateAround speed to directional speed in Unity?

texts:
I am currently using

transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond * Time.deltaTime)

to make an object rotate around another object. This works well, but I want to make the object stop rotating around and instead move in a certain direction at the same speed that it was rotating. However, I can not figure out how to convert the degreesPerSecond into a directional speed.

My goal is to have something like this:

if(rotating) {
    transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond * Time.deltaTime)
} else {
    transform.position += transform.right * DegreesToDirectionalSpeed(degreesPerSecond ) * Time.deltaTime;
}

float DegreesToDirectionalSpeed(int degrees) {
    // Code that I don't know goes here
}

Any tips on how to achieve this?


texts:
In my game the character can fall in two directions. The user clicks right or left button to "push" the character to balance them, so they don't fall. I'm not sure how to increase the forces applied to the character for each press.

function left:touch(e)
    if(e.phase == "began") then
        boy:applyLinearImpulse(-0.5, .5, boy.x, boy.y)
    end
end

function right:touch(e)
    if(e.phase == "began") then
        print("right");
        boy:applyLinearImpulse(2.1, .5, boy.x, boy.y)
   end
end
left:addEventListener("touch", left );
right:addEventListener("touch" , right );


texts: Is a final yield return 0 required in corutines?

texts:
I have the following code run in a coroutine.

I would like to know if the last yield return 0 is necessary and why.

Thank you!

private IEnumerator pChangeFoV()
{
    float duration = 0.7f;
    float zValue = 5f;

    for (float t = 0f; t < duration; t += Time.deltaTime)
    {
        float fNew = Mathf.Lerp(_camera.fieldOfView, zValue, t / duration);
        _camera.fieldOfView = fNew;
        yield return 0;
    }
    _camera.fieldOfView = zValue; //make sure we're really where we want to be

    //now do everything that should be done after we're done with this coroutine

    pEnableSomeScripts();

    yield return 0; //is this final yield return 0 required???
 }


texts: How to ensure my Sine Wave movement starts from the middle-line of the wave

texts:
I am trying to make an enemy for a space game which has Sine style movement. I pretty much have it working how I want, but right now I have to manually fiddle with the 't' value to make  the wave equal on both sides from the starting position x.

I tried first using a real time variable i made from incrementing my 'aliveTime' by Time.deltaTime every update frame.

Then I realised I should probably use its Y position as the timeline because that is what i am trying to base the sideways movement from. But no matter how hard I think (and try random permutations of the formula/code below) I cannot get it to always be 'centred' in the wave (ie. when i change the figures for amplitute and speed_x , it skews the wave off in seemingly unpredictable ways).

Anyone have ideas for what to pass as the 't' parameter in the Mathf Sin line below? (thanks!)

public class Enemy_SineWaveAttack : EnemyBehaviour
{
public float speed_x;
public float amplitute;

protected override void FixedUpdate()
{
    base.FixedUpdate();
    Vector2 vel = rb.velocity;
    vel.x = amplitute * Mathf.Sin(transform.position.y * speed_x); // WHAT CAN I USE HERE TO CENTRE THE WAVE START POSITION?

    vel.y = -Game_Manager.instance.Global_Enemy_Speed * Time.deltaTime;
    rb.velocity = vel;

}
}

Screenshots (if they help to explain what i need) Note, middle enemy is the only one Im talking about here):

See how it moves in wave, but it started the wave from original position and moves to the right from there, and NOT to the left of the original position ever)

Ok, before seeing the answer from DM Gregory I tried my own solution which was to subract half from the overall value of 't' .

I ended up with this and it seems to work with various values for speed and amplitute

 protected override void FixedUpdate()
{
    base.FixedUpdate();
    Vector2 vel = rb.velocity;
    vel.x = amplitute * Mathf.Sin((transform.position.y * speed_x) * 0.5f);
    //vel.x = amplitute * Mathf.Sin(transform.position.y * speed_x - ((transform.position.y * speed_x) / 2f));
    vel.y = -Game_Manager.instance.Global_Enemy_Speed * Time.deltaTime;
    rb.velocity = vel;

}


texts: C# OpenTK - Getting world coordinates of points that are altered by matrices

texts:
I have written a skeletal animation system for a game I am working on. To draw lines that represent a skeleton, I use the GL matrix, and multiply it by each bone a long the body. For example before drawing the left hand, GL.multMatrix has been called for the lower back, upper back, left shoulder, left upper arm and left lower arm.

Currently I am now trying to deal with hitboxes. After this series of matrix transformations have been made, I am drawing a box with the local coordinates of -2,-2,-2 to 2,2,2. This works fine, the animated skeleton has a box around the hand.

However I've reached the stage of actually needing to use the hitbox, to check if it collides with another hitbox. I've worked out the algorithms I shall use for checking if there is a collision, but I first need to change those coordinates from their local to the hand coordinates, into coordinates I can use against other things in the world.

For example the left hand hitbox has the same local coordinates as the right hand hitbox, but how could I change that all back to global coordinates so I can get their proper world coordinates?


texts: Telling which side of a voxel was hit by an object

texts:
In XNA, I have an axis-aligned BoundingBox representing the object's hit box, and a Vector3 representing the object's velocity. I also have a stationary 1x1x1 axis-aligned BoundingBox representing a voxel. Using object.box.intersects(voxel.box), I can tell that they intersect. However, I do not know which side of the voxel was first hit by the object.

I am assuming you can just take the direction from the center of the player to the center of the voxel and use that to determine which face it hit. However, my brain is not working right now and I can't figure out the math.

I already know how to respond when you learn which face was hit (from my previous question). I just don't know how to figure out which face the player hit.


texts: Creating a steady rhythm for music-based game in XNA

texts:
I'm looking to develop a game for Windows Phone which involves the user building notes into a sequencer while playing a puzzle game.

While my implementation is very close to being on-beat there is an occasional pause between beats, which makes the whole thing sound sloppy. I'm not sure how to get around this using XNA's infrastructure.

Currently I'm running this code in the Update method of my GameBoard:

public void Update(GameTime gameTime)
{
    onBeat = IsOnBeat(gameTime);
    [...]
    if (onBeat)
        BeatUpdate();
}

private bool IsOnBeat(GameTime gameTime)
{
    beatTime += gameTime.ElapsedGameTime.TotalSeconds;
    if (Math.Abs(beatTime - beatLength) < 0.0166666)
    {
        beatTime -= beatLength;
        return true;
    }
    return false;
}

private void BeatUpdate()
{
    cursor.BeatUpdate();
    board.CursorPass((int)cursor.CursorPosition % Board.GRID_WIDTH);
}

Update checks to see if the time is on beat. If so, it calls the BeatUpdate method which moves the cursor over the board (sequencer). The cursor reports its X position to the board, which then plays any notes that are in that position on the sequencer. Notes are SoundEffectInstances, pre-loaded and ready to play. TargetElapsedTime is set to 166666, or 60FPS target.

Obviously totaling up the time and then subtracting isn't the most accurate or stable way to go. This current system is just horribly unstable. Beats lag and fire too early and it's obvious. I thought about perhaps some sort of threaded solution but I'm not familiar enough with multithreading to figure out how that would work. How could I fix this?


texts: Understanding unknown mesh data structure

texts:
I have a large number of old mesh files in a custom, undocumented binary format. I have managed to parse almost everything but am left with one group of structures, described below, that I don't understand. I hope an experienced graphics programmer can explain what is happening.

Here are the structures concerned:

// These types are defined below. We're trying to understand what
// these three arrays are used to achieve.
VertexRef vertexRefs[];
Triangle triangles[];
Unknown unknowns[];

struct VertexRef {
    // Earlier in the file, there are several vertex buffers.
    // The file can contain multiple meshes, either as components
    // of a larger mesh, or as multiple LODs.
    // This value _group_ picks out one of these buffers.
    uint8_t group;
    // Index into the vertex buffer picked out by _group_.
    uint16_t vertexIndex;
};

struct TriangleVertex {
    // Index into the array _vertexRefs_
    uint16_t vertexRef;
    // Index into the array _unknowns_
    uint16_t unknownIndex;
};

struct Triangle {
    TriangleVertex verts[3];
};

struct Unknown {
    // Index into the array _vertexRefs_
    uint16_t vertexRef1;
    // Index into the array _triangles_
    uint16_t triangleIndex1;
    // Another index into the array _vertexRefs_
    uint16_t vertexRef2;
    // triangleIndex2 can be 0xffff, while triangleIndex1 never is
    uint16_t triangleIndex2;
};

The array of VertexRef is straightforward. It picks vertices, potentially from multiple meshes, to form a composite mesh.

The array of Triangle is formed by vertices from the array of VertexRef. Each vertex is also associated with an Unknown.

I am out of my depth in understanding what Unknown is doing. Member triangleIndex2 sometimes being 0xffff (or invalid, or nonexistent?) might indicate it is a leaf node of a tree? Perhaps the structure comprising the arrays vertexRefs, triangles and unknowns is some kind of collision detection tree?

I'd be very grateful for any hints. Please ask questions if I've failed to be clear enough about something.

Edit: In answer to a request in comments, I am attaching a sample file and code to load it. The code should run on any likely system. The file is a mesh of a pair of boots. The file is hosted at uploadfiles.io: https://ufile.io/w66mh


texts:
I'm fairly new to C# and Unity, so I don't really know much about it.

I want to create an RTS like game where you have a huge grid that the whole world is placed on. Then you can place houses, walls etc on the tiles just like a lot other RTS games (i.e. Age of Empires, Stronghold Series etc).

How would I go about this in Unity? I could imagine having some Terrain/World manager that handles all the models and objects that you can interact with etc. And probably a lot of prefabs too with the different items, soldiers and so.

So if anyone have any smart way of doing this or maybe a link to a tutorial explaining, then the help would be greatly appreciated.


texts: How can I mimic an isometric perspective using square tiles?

texts:
Can an isometric perspective be mimicked with traditional square tiles? Can't the effects of the 45-degree overhead view simply be "drawn in" to the square? How would this work?

Picture this: the tiles themselves are square (not diamond) but all objects placed on them (sprites, terrain objects like trees, buildings, etc) are drawn from isometric view as if they were on diamonds.

This might be a silly question to ask, but I'm having difficulty understanding isometric perspective.


texts:
Googling around, a way for calculating framerate and displaying it as text ingame is using 1/Time.deltaTime. However, comparing this against unity stats FPS shows 2 different FPS. Which of it is incorrect? If 1/Time.deltaTime is incorrect, how does one go about calculating FPS?

Below is a screenshot of the FPS difference, as seen in the profiler, fps is well below 100 FPS whereas calculated FPS stays around 60.


texts: Godot Animation only playing First Frame

texts:
I have tried checking if it is already playing, stopping animations before and putting it in a separate function. Whenever I jump it should play 4 Frames of my animated sprite. But it only plays first.

const FLOOR = Vector2(0,-1)
const SPEED = 500
const GRAVITY = 20
const JUMP = -600

func _physics_process(delta):
    pos.y += GRAVITY
    if Input.is_action_pressed("ui_right"):
        pos.x = SPEED
        $Sprite.play("Run")
        $Sprite.flip_h = false
    elif Input.is_action_pressed("ui_left"):
        pos.x = -SPEED
        $Sprite.play("Run")
        $Sprite.flip_h = true
    else:
        pos.x = 0
        $Sprite.play("Idle")
    if is_on_floor():
        if Input.is_action_just_pressed("ui_up"):
            pos.y = JUMP
    else:
        if pos.y < 0:
            $Sprite.play("Jump")
        else:
            $Sprite.play("Fall")
    pos = move_and_slide(pos,FLOOR)
```


texts:
I have taken as a practice (as many others, I think) to always do this when working with pointers:

void I_take_pointer(some_type* arg1)
{
    if(arg1)
    {
        //safely do stuff with pointer
    }
    //optionally an else statement
}

...in almost all functions, except those where I can be sure arg1 will never be null.

Is it good practice/should I perform this check on the SDL_Event* I get on input when working with SDL2?


texts: Converting between Spiral Honeycomb Mosaic and axial hex coordinates

texts:
There seems to be quite a lot of logic in dealing with hexagonal grids using a system of axial coordinates like the one described here.

In doing some reading about hex grids, though, I ran across the notion of the Spiral Honeycomb Mosaic (the links on that mirror are broken; the content is copied from here, about halfway down the page). It seems to be used mostly in image processing, but it's interesting from the standpoint that it assigns each hex a unique, sequential base-7 number as its identifier.

I'm not sure that it's actually useful for anything, but I'm wondering: is it possible to convert back and forth between the SHM numbering system and axial coordinates?

Both systems have methods to convert from a hex to the Cartesian coordinates of its center, so presumably one could calculate that out of one system, and then into the other. But that's messy and inefficient, and I'm convinced it's possible to do better.

Because of the fractal nature of the SHM, the conversion routine in the sample code provided relies on a loop; it seems like the general solution might involve a series?


texts: main camera not covering whole screen in unity3d

texts:
I have been using unity and i got a problem where my main camera is covering only the first half of the floor i made.
camera position is left and the floor is rotated ,i m posting an image please help .
I have shown a player white coloured and an enemy pink coloured .player is not shown as you can see.


texts: Selecting a range of hex tiles within radius of main tile

texts:
What I'm doing is pretty new to me, or at least I think it is, so I'm not really sure of what I'm looking for. Hopefully someone here knows =-)

Using a grid of hexes I generate, I can hover over any tile and it will highlight just fine. Now what I'm trying to figure out is how to allow for a radial selection of tiles around that hovered tile (brush size, basically), eventually allowing for a somewhat radial soft-selection gradient to allow falloff.

Each hex already knows about their neighbors, so currently I am hard-coding logic to handle a radius of 1, 2 or 3. I could duplicate that logic over and over to handle bigger radii but this is definitely not going to work for much longer, so I am trying to figure out a more efficient and cleaner way using loops/recursion/whatever.

Can anyone offer any pseudo-code or possibly a link that explains how to do this? Below is a (probably bad) attempt at what I think it would look like.

OnMouseOver(){
    // This would select a radius of x hex tiles including center tile
    this.SelectTile(3);
}

SelectTile(selectionRadius){
    if(!this.alreadySelected){
        this.Select();
    }
    for(int i = 0; i <= selectionRadius; ++i){
        if(i < selectionRadius){
            foreach(HexTile tile in thisTile.neighbors){
                tile.SelectTile(selectionRadius - i);
            }
        }
    }
}

Edit: I'm using this fantastic resource to help with hexes - http://www.redblobgames.com/grids/hexagons/ - so might there be a section on this page that may explain what I need and I'm just missing?


texts:
I've implemented the Möller-Trumbore algorithm but I hit some false positive:

Ray: vec3(2.100000, -1.000000, 3.314214), vec3(0.685786, -1.000000, 1.900000)
Collide with: vec3(1.000000, 1.000000, -0.999999), vec3(0.999999, 1.000000, 1.000001), vec3(1.000000, -1.000000, 1.000000))
uvt=vec3(0.435307, 0.198000, -1.603999)

If I draw the collision, I see clearly that the ray does not intersect with the triangle.

From this site: http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection
I wrote this code:

bool Node::rayIntersectTriangleDebug(const glm::vec3 orig, glm::vec3 dir
                       , const glm::vec3 vert0, const glm::vec3 vert1, const glm::vec3 vert2
                       , glm::vec3 &result)
  {
    //dir = glm::normalize(dir);

    const glm::vec3 edge1 = vert1 - vert0;
    const glm::vec3 edge2 = vert2 - vert0;
    const glm::vec3 pvec = glm::cross(dir, edge2);
    const float det = glm::dot(edge1, pvec);

    const float Epsilon = std::numeric_limits<float>::epsilon();

    if (det > -Epsilon && det < Epsilon)
      return false;

    const float invDet = 1.0f / det;

    const glm::vec3 tvec = orig - vert0;

    result.x = glm::dot(tvec, pvec) * invDet;
    if (result.x < 0.0f || result.x > 1.0f)
      return false;

    const glm::vec3 qvec = glm::cross(tvec, edge1);

    result.y = glm::dot(dir, qvec) * invDet;
    if (result.y < 0.0f || result.x + result.y > 1.0f)
      return false;

    result.z = glm::dot(edge2, qvec) * invDet;

    const float abs = std::abs(result.z);
    const float dist = std::abs(glm::distance(orig, dir));

    const glm::vec3 intersection = vert0 + result.x * edge2 + result.y * edge1;

    if (abs < dist)
      {
         return true;
      }
     return false;
  }

Also I'm not sure if I have to normalize my direction vector.

EDIT

I've red here that

  I'm not sure if it should be normalized or not, but tests I've
  conducted over a normalized version yelded valid results

I've tried to normalize my direction with the following code without success:

const glm::vec3 dir = glm::normalize(officialDirection - orig);


texts: Drawing rectangle around a target on screen

texts:
I am just started with Unity and C#. I need in my work to do rectangle on a scene. I have a 3D scene, say some warehouse and there is an object. Camera is animated and moving towards the object. Is it possible to draw a rectangle around the object on the camera screen while the camera is moving unless the object on the screen? The task is like keeping target in war-flight games.
This is my code, where I tried to draw rectangle anywhere:

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

public class MY_getting_images : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject pallet;
    public Camera color_cam;
    public Vector3 pos;
    LineRenderer l;
    void Start()
    {
        pallet = GameObject.Find("PalletWood01");
        l = pallet.AddComponent<LineRenderer>();
        List<Vector3> ps = new List<Vector3>();
        ps.Add(new Vector3(0, 0));
        pos = pallet.transform.position;
        ps.Add(new Vector3(10,10));
        l.startWidth = 1f;
        l.endWidth = 1f;
        l.SetPositions(ps.ToArray());
        l.useWorldSpace = true;
        /* Finding camera in a scene: tag needed camera, for example "Player", and then GameObject.FindWithTag("Player").GetComponent<Camera>();
         * Tag the camera another way for deployment
               */
        color_cam = GameObject.FindWithTag("Player").GetComponent<Camera>();
        /*pos = color_cam.transform.position;
        pos = pallet.transform.position;
        Debug.DrawLine(Vector3.zero, new Vector3(0, 0, 5), Color.red);
        Debug.Log(pos);*/
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(pos);
        /*pos = color_cam.transform.position;
        Debug.Log(pos);*/
    }

}

The scene now looks like on the image above:

I want 2d rectangle around the pallet drawn on the screen.


texts: AS3 .hitTestObject() not working with Tween function

texts:
(This was originally in an other senction but many told me to ask here, hopefully someone can answer this)
I am having a major problem in my new browser app.

Okay so I made game where different cubes (squares) spawn at the top of the screen and I use the Tween class to make them go down the screen and then disappear.

However I want to detect a collision when a cube hits the player (that is also a flying cube).

I tried everything, truly everything but it does not seem to work. The problematic thing is that when I remove the "Tween" function it does detect collision with the hitTestObject method but when I add the "Tween" line collision won't be detected anymore.

The code looks like this:

    function enemiesTimer (e:TimerEvent):void {

newEnemy = new Enemy1();
  layer2.addChild(newEnemy);
  newEnemy.x = Math.random() * 700;
  newEnemy.y = 10;
  if (enemiesThere == 0)
  {
      enemiesThere = true;
      player.addEventListener(Event.ENTER_FRAME, collisionDetection)
  }

  var Tween1:Tween = new Tween(newEnemy, "y", null, newEnemy.y, newEnemy.y+distance, movingTime, true); }

The collision detection part:

private function collisionDetection (e:Event):void
  {

      if (player.hitTestObject(newEnemy))
      {
          trace("aaa");
      }

  }

*Another weird thing is that the collision detection works only in the starting point, where the squares spawn but they aren't really there anymore so I don't quite get it.

I hope someone can answer this and maybe tell me how I can code this. Thanks in advance :)

*I've tried out Tweener & TweenMax as well, the problem is always the same


texts: How do I detect a given sprite's bounds automatically using Java?

texts:
Background

I have the following png file that contains the player sprite.

As with any png file, the non-colored pixels are transparent.

(Width: 16px; Height: 16px)

Currently, I can erect a rectangle (collision-bounds), using java.awt.Rectangle around the image using the image's width and height, as seen below.

I would like to crop the image so that the width and height are changed to the edges of the colored portion of the image, much like what is shown below.

This will allow for more accurate collision-detection between entities or objects in a game.

I want to construct a method that handles this modification dynamically, as seen below.

//Method calculates how far in from [top, bottom, left and right]
//the [non-zero] or [transparent] pixel-data of an image are
//in order to construct a new image that starts at the edges
//of the colored portion of the image.
public BufferedImage adjustImage(BufferedImage image)
{
    BufferedImage result = null;

    return result;
}

Problem

However, I am uncertain as to the algorithm to use to achieve the result above.

Can anyone give a step-by-step on how to detect these bounds and how to implement such a fuction as described above?


texts: Why do most video game guns reload without losing unused ammo in the magazine?

texts:
If I have picked up 500 spare ammo and I 73/100 bullets in my current gun, why will I end up with 473 spare ammo instead of 400 (losing the 73 unused rounds in the previous magazine)?

Is this just to make it easier on the player?

I want to make a challenge shooting game and it seems like timing your reloads would be interesting.

Is there any reason I should stick to the norm?


texts: How do games implement client/server frame rate?

texts:
Do games have a frame rate at X fps that updates logic and also renders?

Or do games update logic at a much slower frame rate than rendering?  Let's say 20-25 fps for logic, and 60+ fps for rendering.

I am writing a game engine and I am a bit confused on how frame rate is handled.

If I were to run logic slower than rendering, then wouldn't I just be wasting the rendering frames because it is rendering the same thing over and over...? Unless I also interpolate the rendering with a delta.

I have read some game servers run at a much slower frame rate (let's say 20 FPS), so shouldn't the client also run logic at 20 FPS?


texts: How can I make a custom mob that looks like the Enderman?

texts:
I have previously made two other mods that added in mobs. In order for the mob to look like a wolf, I needed the wolf.java file (Found online).

Without setting a defined java file, the mob will use the villager's java file, which can lead to some messed up mobs.

Now, I have a requirement that a mob looks like the Enderman; how would I achieve this?


texts: Are concurrent Update and Draw calls possible in XNA?

texts:
I am making a real-time game in XNA and I would like to reduce the Update() call frequency while getting as many Draw() calls as possible. This would enable the program to finish long calculations in the Update() method while Draw() is still regularly called to perform interpolation and rendering to have the game appear running smoothly.

But, it seems like Draw() is never invoked before Update() has finished. This creates stuttering.

Is it possible to achieve concurrent calls to Draw() before Update() has finished?


texts: 2D Isometric Movement - Move to Mouse Position

texts:
I'm developing a 2d isometric game on a engine made by myself (as a way to practice Java), however i'm stuck on what it seems to be a math problem.
I wish I could have some help on how to implement a 360 degree movement system based on Mouse Position, where the character angle will be the mouse angle, and the mouse angle is defined based on the center point the screen itself. The screen work like a compass, and where you click on it, it will set the angle and character should walk following said angle.
But trigonometry is by no means one of my strenghts, i'm struggling on how to determine the angle, then, how to set a formula to change the Y and X velocity based on the angle found.
Example, my native resolution is 512x288. Center point is 256x144. So, If I click in in the coordinate of X = 256 and Y is 0~144, the character should walk on a perfect stright line upwards. If Y is 145~288, then, a perfect line downwards.
Any help is welcome!
Edit: The camera is always fixed on the character, so it will always render on the middle of screen.
So far I've only managed to get basic movement through mouse by adding 8 hitboxes on screen, and set the angle based on which box the mouse clicked. For the speed, it's a hardcoded switch case on angle value, like, angle = 90, vel_x = 0, vel_y = -10.


texts:
I'm working on a 2D game which involves firing projectiles around a solar system and having the path of the projectile change based on the gravitational pull of solar bodies.

I've been trying to find an explanation for how orbital mechanics work, at least in this simplified 2D scenario, but so far haven't found anything other than theoretical high-math documents.

I know that there are some existing games that do this already in 3D space, namely Planetary Annihilation and Interplanetary, but I haven't been able to find any references to how they did it. The Planetary Annihilation devs did a livestream demo of it once, but I haven't been able to find it since, and I don't think it went into much detail.

Whether by explanation or reference, does anyone know how 2D orbital mechanics work for the purpose of a game? How or where can I learn this?


texts:
This was my original question:
Populating Sprites
I used the following code to spawn Enemy Sprites in my game. I have 2 types that I was using and it would display one then remove it and display the other. It did this repeatedly(Imagine someone playing with a light switch and you have what is happening with the NPCs. EnemyType1 is Off and EnemyType2 is On.).Also It does not apply the current level number meaning, it does not spawn the number of enemies for the level. The number of enemies I want to spawn is the exact number of the level.  I used other types of random methods( nextBoolean(), nextInt(), nextFloat() ). I showed the code to my friend and he told me that I would need to spawn them outside of my loop, but he did not know how to. So now I am trying to see if anyone on stack could help me. What I am trying to do is this:

NPC's = Enemies

I have 2 types of NPC's that I want to use. The number of Enemies that are spawned are equal to the the current level number. I want to be able to spawn how ever many is needed for that level and have it to where which Enemy that will spawn is random, so you don't know if you will get EnemyType1 or EnemyType2 or a Mix. Ex: Level 1, only 1 Enemy spawns, the type is random. Level 2, only 2 Enemies spawn, the type is random. Level 3, only 3 enemies spawn, the type is random. etc.

Thanks In Advance.


texts: I would really like to write a script for a game, but do I have a chance?

texts: I'm 18 and am very good a reading writing and storytelling. I would like to write out the concept script and scenes for a vdeogame. I have a High School diploma but at the moment no other formal schooling. I would like my dream to become a reality, a game I wrote that gets created by a big name developer and published for everyone to enjoy. Before I start writing though I want to know is this achievable from the position I stand in now?


texts:
I'm interested in researching coding techniques for coding relationships in games. I'm trying to look for resources, but haven't really come across anything yet.

More specifically, in games where playable characters can build relationships with different characters, and especially in games where there is interaction between these relationships. I've heard that the most recent Witcher game is good at this. I imagine that they're not discussing their code openly, but am just using that as an example, if it's helpful.

I would assume the basic technique is to have the non-playable characters have a basic score attached to them that measures their affinity to the playable character which is then effected by player choices. Let's talk about Alice, Bob, and Charlie, where Alice is the playable character, and Bob and Charlie are non-playable (NPCs). I'll throw up some Python psuedocode, assuming separate classes for playable characters :

new Alice(playable):
    code would go here

new Bob(nonPlayable):
    self.affinity = 0

new Charlie(nonPlayable):
    self.affinity = 0

Then if Alice did something nice to/for Bob, maybe it would trigger something that would include:

Bob.affinity += 5

If Bob and Charlie are rivals, and Alice does something nice for Charlie, perhaps it would trigger:

Bob.affinity -= 5
Charlie.affinity += 5

With various events, responses having a requirement of having a relevant affinity score either above or below a certain threshold.

The weakness of such a system is that it only measures affinity to the playable character, and is limited to one trait score, at that. What I mean by the latter is that there's no nuance to it - it's almost as if the NPC totally likes everything about the player, or totally hates everything about them.

I'm hoping for something more dynamic. I'll list a couple complex points, though I'm not necessarily looking for something that covers every single point of nuance here, more for an approach.

Traits that interpret how characters would react to events. A basic idea might include events that have scores in a few categories, and then characters react based on their own scores. This might be a step in allowing randomly generated characters. Carrying on with the Python examples, I would suppose events should be a class of their own with traits on them:

class Event():
        self.courage = 0
        self.justice = 0
        self.otherTrait = 0

I'm not sure how to really individualize this, though. How would I have the event react to Alice getting along with Charlie and not Bob? What about having a tight working relationship with Bob, but a warmer one with Charlie, though Dana feels competitive with Alice, etc? Put into a more concrete question, how would I code an event to react to a very diverse range of possible factors?

Nuanced relationships with characters. An NPC might trust a player in combat, but hate them socially. A problem here would quickly become the amount of hardcoded dialogue rising exponentially. This might need the ability to generate text too. If so, this leads to a more concrete question, which is there a known way to generate text conforming to a set of moods and feelings? This would also be a boon in randomly generated NPCs. I was wondering if there's something layered on top of Word2Vec or something like that.
 -

Thanks!


texts: Lat, Lon and elevation Conversation into unity coordinates

texts:
I have came across a very vague project problem and its feasibility report or communication procedures I have to define. And here is the current scenario:

I have two applications
One is built on Unity3d (which is under my control)
The second  is also an application (which i don't know, and not under my
control-) but it is related to a map service app.

Now the actual thing I want to do is that: If a user click in the map application than, the touch should be recognize in the unity application too.

Suppose I have able to communicate with both applications and the map application providing me the latitude, longitude and elevation information on-click. Now the question is how do I convert its lat, lon and elev into my project work-space/unity coordinates?. I found 3D coordinates on a sphere to Latitude and Longitude, and its about sphere. I don't have sphere I have an environment where different models are placed precisely according to map (there is no dummy models, all are accurate) and the map projection is based on snake-grid.


texts: What are some ideal algorithms for Rogue-like 2D dungeon generation?

texts:
What are some good resources regarding procedural content generation in the context of dungeon generation?

Closest article I could find was Algorithm for generating a 2d maze, which isn't quite what I'm looking for. Features, such as rooms and connected hallways, are ideal.

Thanks!


texts:
I'm adding leaning to my player controller and I can't find out how to stop the rotation overriding the tilt
  void Look() {
      transform.Rotate(Vector3.up * Input.GetAxisRaw("Mouse X") * mouseSensitivity);

      verticalLookRotation += Input.GetAxisRaw("Mouse Y") * mouseSensitivity;
      verticalLookRotation = Mathf.Clamp(verticalLookRotation, -90f, 90f);

      cameraHolder.transform.localEulerAngles = Vector3.left * verticalLookRotation;

  }

  void TiltCamera(float angle) {
      cameraHolder.transform.rotation = Quaternion.Euler(0, 0, angle);
  }

Thanks