texts: UE4 - projectile that turns into an enemy?

texts:
I'm wondering what would be the best way to do this:
A boss enemy tosses a smaller enemy as a projectile. After landing the thrown enemy starts behaving like a normal enemy with walking, shooting etc.

My ideas would be either to make an enemy blueprint that has this behavior defined (for example, all the "normal" behavior is turned off until it lands), or to make two classes, the projectile and the enemy... then somehow convert them?

But how would I do it? I'm more interested in the latter method. The first one I could figure out myself. So how would I change the projectile to an enemy? Define some casting? Destroy the projectile and immediately spawn an enemy?

EDIT:
What is really interesting to me is the technical side of the problem.
If we go with the route of enemy who starts as a projectile and turns into a walking enemy, that would probably involve 2 sets of AI (I'm just grasping that, forgive me) and some trigger to switche between them, like hitting a wall. Seems simple.

If we go with the route of 2 classes, the transition is what bothers me. The most simple way would be to destroy the ProjectileEnemy and spawn the Enemy from it. That obviously won't work - after destroying Projectile enemy, there's nothing to call "Spawn" method. I have a crude workaround, spawn Enemy first and immediately after - destroy ProjectileEnemy. Won't that cause visual issues and other problems though?


texts: Why are my waves not spawning as expected?

texts:
Hey guys so here's an outline of my problem using a basic 3-step approach

The Problem Defined
Waves 1-22 should spawn in order with the correct paths and enemy prefabs. However, Waves 1-4 only spawn and repeat on a loop.
https://www.youtube.com/watch?v=p0HZ_qo4SxU

Possible Causes
I think the issue possibly lies within my enemyspawner.cs script but it could also potentially lie within my level.cs and waveconfig.cs scripts. Oddly enough this seems to also be an issue with the original source code as well. I made several copies of the prefabs, gave them unique paths and waves and changed the new enemy prefabs to different colors to test it and the same result happens. https://www.youtube.com/watch?v=8zr7CVjty6k

The needed solution
I need all 22 waves to re-spawn in order correctly as only having 4 waves repeat is very repetitive and boring.

Here is my specific code for enemyspawner:

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

public class EnemySpawner : MonoBehaviour {

    [SerializeField] List<WaveConfig> waveConfigs;
    [SerializeField] int startingWave = 0;
    [SerializeField] bool looping = false;

    IEnumerator Start()
    {
        do
        {
            yield return StartCoroutine(SpawnAllWaves());
        }
        while (looping);
    }

    private IEnumerator SpawnAllWaves()
    {
        for (int waveIndex = startingWave; waveIndex < waveConfigs.Count; waveIndex++)
        {
            var currentWave = waveConfigs[waveIndex];
            yield return StartCoroutine(SpawnAllEnemiesInWave(currentWave));
        }
    }

    private IEnumerator SpawnAllEnemiesInWave(WaveConfig waveConfig)
    {
        for (int enemyCount = 0; enemyCount < waveConfig.GetNumberOfEnemies(); enemyCount++)
        {
            var newEnemy = Instantiate(
                waveConfig.GetEnemyPrefab(),
                waveConfig.GetWaypoints()[0].transform.position,
                Quaternion.identity);
            newEnemy.GetComponent<EnemyPathing>().SetWaveConfig(waveConfig);
            yield return new WaitForSeconds(waveConfig.GetTimeBetweenSpawns());
        }
    }
}

Here is my specific code for waveconfig:

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

[CreateAssetMenu(menuName = "Enemy Wave Config")]
public class WaveConfig : ScriptableObject
{

    [SerializeField] GameObject enemyPrefab;
    [SerializeField] GameObject pathPrefab;
    [SerializeField] float timeBetweenSpawns = 0.5f;
    [SerializeField] float spawnRandomFactor = 0.3f;
    [SerializeField] int numberOfEnemies = 5;
    [SerializeField] float moveSpeed = 2f;

    public GameObject GetEnemyPrefab() { return enemyPrefab; }

    public List<Transform> GetWaypoints()
    {
        var waveWaypoints = new List<Transform>();
        foreach (Transform child in pathPrefab.transform)
        {
            waveWaypoints.Add(child);
        }
        return waveWaypoints;
    }

    public float GetTimeBetweenSpawns() { return timeBetweenSpawns; }

    public float GetSpawnRandomFactor() { return spawnRandomFactor; }

    public int GetNumberOfEnemies() { return numberOfEnemies; }

    public float GetMoveSpeed() { return moveSpeed; }

}

Here is my specific code for Level:

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

public class Level : MonoBehaviour
{

    [SerializeField] float delayInSeconds = 2f;

    public void LoadStartMenu()
    {
        SceneManager.LoadScene(0);
    }

    public void LoadGame()
    {
        SceneManager.LoadScene("Game");
        FindObjectOfType<GameSession>().ResetGame();
    }

    public void LoadGameOver()
    {
        StartCoroutine(WaitAndLoad());
    }

    IEnumerator WaitAndLoad()
    {
        yield return new WaitForSeconds(delayInSeconds);
        SceneManager.LoadScene("Game Over");
    }

    public void QuitGame()
    {
        Application.Quit();
    }

}


texts: Unity, errors when using Quaternion.Euler to copy rotations

texts:
In the game I'm creating I have a square that rotates around a parent point, I want the square to always aim upright however (think of a rotating platform). What I've done is simply use
child.transform.rotation = Quaternion.Euler(0.0f, 0.0f, -gameObject.transform.rotation.z)
This rotates the child object in the opposite direction so that they're always aiming in the right direction. Except it doesn't, there is some error that piles up with bigger rotations. For example at 90º the child object will be rotated -90.77 instead which is very noticeable given that the game has a grid of sorts and when objects are not aligned to it they instantly pop out.

So my question is, is there any way to avoid this error?


texts: How to position a Weapons model in a first person shooter with XNA

texts:
I am building a first person shooter and positioning the weapons is hard. I am trying to get the bat to look like you are holding it but I keep trying things and they don't appear in the positions I want them to be in. Here is what I did with one version of the function.

void DrawModelModel(Model model, Matrix world)
    {
        Vector3 modelPosition = Vector3.Zero;
        float modelRotation = 0.0f;
        Viewport viewport = graphics.GraphicsDevice.Viewport;
        float aspectRatio = (float)viewport.Width / (float)viewport.Height;
        // Set the position of the camera in world space, for our view matrix.
        Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 200.0f);
        // Copy any parent transforms.
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        // Draw the model. A model can have multiple meshes, so loop.
        foreach (ModelMesh mesh in model.Meshes)
        {
            // This is where the mesh orientation is set, as well
            // as our camera and projection.
            foreach (BasicEffect effect in mesh.Effects)
            {

                effect.World = transforms[mesh.ParentBone.Index] *
                    Matrix.CreateRotationY(modelRotation)
                    * Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f);
                effect.View =  Matrix.CreateLookAt(cameraPosition,
                    Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(35.0f), aspectRatio,
                    1.0f, 10000.0f) ;
            }
            // Draw the mesh, using the effects set above.
            mesh.Draw();
        }
    }

Here is what I did with a different version of the function.

void DrawModelModel(Model model, Matrix world)
    {
        Vector3 modelPosition = Vector3.Zero;
        float modelRotation = 0.0f;
        Viewport viewport = graphics.GraphicsDevice.Viewport;
        float aspectRatio = (float)viewport.Width / (float)viewport.Height;
        // Set the position of the camera in world space, for our view matrix.
        Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 200.0f);
        // Copy any parent transforms.
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        // Draw the model. A model can have multiple meshes, so loop.
        foreach (ModelMesh mesh in model.Meshes)
        {
            // This is where the mesh orientation is set, as well
            // as our camera and projection.
            foreach (BasicEffect effect in mesh.Effects)
            {

                effect.World = transforms[mesh.ParentBone.Index] *
                    Matrix.CreateRotationY(modelRotation)
                    * Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f);
                effect.View =  Matrix.CreateLookAt(cameraPosition,
                    Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveOffCenter(-2.0f,1.0f, 0.0f, 1.0f, 1.0f, 10000.0f) ;
            }
            // Draw the mesh, using the effects set above.
            mesh.Draw();
        }
    }

What matrix can I use to get the bat model to appear realistically as if you are really holding it in a first person view. I am new to matrices so my knowledge of them is basic. What matrix should I use or what parameters with my current matrix should I be editing? I am thinking the projection matrix is what I need to be editing, but I am very confused at this point. Any help would be great.


texts: Why does the kinematic body move in opposite direction after I interpolate its movement, and how do I fix it?

texts:
I have added some basic movement and some manual interpolation to a cube that is a kinematic body in Godot.
extends KinematicBody

var speed : int = 10
var slowdown_buffer = 0.2
var movement = Vector3(0,0,0)
func _ready():
    pass

func interpolate():
    if movement.x > 0:
            movement.x -= slowdown_buffer
    elif movement.x < 0:
        movement.x += slowdown_buffer
    else:
        movement.x = 0.0
func _physics_process(delta):
    if Input.is_action_pressed("left"):
        movement.x = -speed
    elif Input.is_action_pressed("right"):
        movement.x = speed
    else:
        interpolate()

    move_and_slide(movement)

The problem is that when I move the cube using A and D, after the cube stops after the interpolation, it starts moving in the opposite direction with a non-increasing speed.
How can I fix this?


texts:
tl;dr How can one enforce that groups of players stay together in units in Minecraft?

I'm developing a plugin for a Minecraft server. It's based off feudalistic societies, like Ancient Europe or Japan. I understand that many ancient societies had advanced battle tactics (like this and this, for example). I think this is very interesting, and would add some more interest to a server.

However, Minecraft isn't particularly well suited for this kind of play. Generally, in battles, all the players just run willy-nilly and charge the enemy. There are no units of players, much less the units combining in a smart way to defeat the enemy. How can one enforce players staying together in one unit or group? Keeping each player in a certain position no matter what is not an option, since the players cannot PvP. Once players are grouped into units, I assume they will take up certain battle strategies and use them in a smart way.


texts:
I am creating a 3d game ( a car racing game) using opengl ES.
i know the rendering concept and also using a physics engine for all the physics stuff.
All modeling is done using 3d modeling softwares.

Now my question how to do the special effects within a game.

For example like when a car collides and toggle how to slow down all the environment effects which i saw in other available games.
OR
Nitrogen gas effects in a car race game.

Any suggestions will be of great help.
I guess my question is clear, if not feel free to ask anything.


texts: What are these yellow lines between toggles, and how do I turn them off in Unity?

texts: I don't understand what these faint yellow lines are and how to turn them off (see screen shot). I have created toggles from a prefab and to save time have been duplicating them and moving them. Unity chugs everytime I move a group of them, and I imagine it is because it is recalculating how to draw these lines. All of the toggles have lines between them. Send help!


texts:
I have two canvases, both of them having a UI element on them.
At some point, both canvases will be active in the game (I just act like so, I want to make sure that my game works even if that's the case) and I want one of them to never block the other canvas's layer.

These two, let's say Canvas1 is on layer UI and is responsible for character jumping.
Canvas2 is on layer toggle time scale and it's job is to switch between timescale 0 and 1.
I want Canvas2 to be ALWAYS accessible, so its layer, toggle time scale is NOT blocked by the first canvas.
I tried messing around with the Blocking Mask but that didn't help, sometimes the ray still gets blocked out. How to set up those Blocking Masks for my canvases to work?


texts: Improving SpriteBatch performance for tiles

texts:
I realize this is a variation on what has got to be a common question, but after reading several (good answers) I'm no closer to a solution here.  So here's my situation:

I'm making a 2D game which has (among some other things) a tiled world, and so, drawing this world implies drawing a jillion tiles each frame (depending on resolution: it's roughly a 64x32 tile with some transparency).

Now I want the user to be able to maximize the game (or fullscreen mode, actually, as its a bit more efficient) and instead of scaling textures (bleagh) this will just allow lots and lots of tiles to be shown at once.  Which is great!

But it turns out this makes upward of 2000 tiles on the screen each time, and this is framerate-limiting (I've commented out enough other parts of the game to make sure this is the bottleneck).  It gets worse if I use multiple source rectangles on the same texture (I use a tilesheet; I believe changing textures entirely makes things worse), or if you tint the tiles, or whatever.

So, the general question is this:

  What are some general methods for improving the drawing of thousands of repetitive sprites?

Answers pertaining to XNA's SpriteBatch would be helpful but I'm equally happy with general theory.  Also, any tricks pertaining to this situation in particular (drawing a tiled world efficiently) are also welcome.

I really do want to draw all of them, though, and I need the SpriteMode.BackToFront to be active, because I use the layering quite essentially.

I don't have any easily digested sample code since the method has become somewhat complicated, but no extra tiles are being "drawn," and all the drawing is inside one SpriteBatch.Begin / SpriteBatch.End call.


texts: Do any games have this type of mechanic?

texts:
This question got closed on gaming SE as off topic. I hope it's on topic here.

Many years ago, a friend and I prototyped a simple 2d rpg with what we thought was a unique idea for the combat mechanics. It used wandering monsters and a cutaway battle screen system. We added a bunch of effects like "conditions" that could affect your player - the standard stuff like blind, dazed, weak, etc.

The unique part is that we wanted to make the combat as close to you, the player actually fighting, and not just you commanding a character to do stuff. So we made it so what the character experiences, you experience. The basic combat screen included an outline of the enemy, and one of you. At randomized times, targets would appear on either figure, and begin to shrink. On the enemy, these were "openings" and you had to click them before they disappear, the closer to center, the better the hit. On your figure, you had to click to defend from an attack before the target shrank.

The conditions on your character made this interesting. Like I said, they were intended to affect the player literally. So blindness literally dimmed the screen 90%. If you were dazed, the targets would wobble randomly. If you were weak, your mouse cursor would lag and glide around. Everything translated to an actual impairment in your gameplay, not some arbitrary "your attacks do half damage".

This would have logically extended into a spell system, where you actually have to remember spell words and combine them into creative combinations and type them real time. I know some games have done variants of this kind of spell system.

Looking back, I think this was still a fun idea, but it seems awful from an accessibility standpoint. Players like their games to make them feel powerful, not to acknowledge and emphasize their real life flaws. So have any games attempted something like this and had some success? What came of it? If not does it seem like a reasonable and creative idea to try?


texts: How do I display an image after pressing an UI button in unity3d?

texts:
I am working on a game in unity3d in which I want to display the details about the players when a button is being pressed.
Suppose there are 12 players so for that I will have to make 12 UI buttons as well and I have done that too but the problem is that how to display image after clicking the buttons?
If anyone knows please sort out my problem, any help would be more appreciated.
Thanks in advance


texts: Phone crash when try to use vibration on Android

texts:
Im developing an app that when you click a button the phone has to vibrate, the issue is that the phone just chashes. Saing that I need permitions to vibrate. I've already set this permition in the build.setting (android manifiest).

Here is the code

build.settings:

settings =
{
orientation = {
    default = "portrait",
    supported = { "portrait", }
},

iphone =
{
    plist=
    {
        CoronaUseIOS7LandscapeOnlyWorkaround = true,
        CoronaUseIOS7IPadPhotoPickerLandscapeOnlyWorkaround = true,
        CoronaUseIOS6LandscapeOnlyWorkaround = true,
        CoronaUseIOS6IPadPhotoPickerLandscapeOnlyWorkaround = true,
        UIApplicationExitsOnSuspend = false,
        UIPrerenderedIcon = true,
        UIStatusBarHidden = false,
        CFBundleIconFile = "Icon.png",
        CFBundleIconFiles =
        {
            "Icon.png",
            "Icon@2x.png",
            "Icon-60.png",
            "Icon-60@2x.png",
            "Icon-72.png",
            "Icon-72@2x.png",
            "Icon-76.png",
            "Icon-76@2x.png",
            "Icon-Small.png",
            "Icon-Small@2x.png",
            "Icon-Small-40.png",
            "Icon-Small-40@2x.png",
            "Icon-Small-50.png",
            "Icon-Small-50@2x.png",
        },
    },
},
android =
{
    permissions =
    {
        { name = ".permission.C2D_MESSAGE", protectionLevel = "signature" },
    },
    usesPermissions =
    {
        "android.permission.INTERNET",
        "android.permission.VIBRATE",
    },
},
}

the file that uses the vibration is:

local onButtonEvent = function (event )

        system.vibrate()
end

I read all post in Corona page without success.
Can I see the android manifest to see if the permissions are there.
I've read that is a Corona issue not sure.


texts:
I was working with the OGRE .NET bindings (MOGRE) for quite a long time. To improve my (not that good) C++ skills, I am switching from C# to C++.

After implementing a basic OGRE application, I was curious why Ogre has it's own String class Ogre::String?
Why is it used and not std:string?

Can/shall I mix these String types and what shall I use in my OGRE application for non-OGRE tasks/methods?


texts: How does Unity know that you make more than one hundred thousand dollars on the Personal plan?

texts: How do they check if you make more than 100k? That is really puzzling me.


texts: Networking - How does server fixed-timestep work?

texts:
I'm making a server/client model for a top-down 2d shooter. Because I need to calculate collisions with walls & other players using a small delta, I want to use the fixed-timestep model like in this example: https://gafferongames.com/post/fix_your_timestep/. Apparently this is a common approach for network games.

Right now my model looks something like this:

Client connects and is synced to the current server tick (let's say
tick is 50)
Client sends its first input + the time pressed (local tick 50) to the server
Server receives the message at tick 55. Because the message was for tick 50 which has passed, this request is ignored.

As I understand it, the client and server run at the same rate, but because of latency the client sends messages too late and all get ignored. Am I supposed to let the server run a few ticks behind the client somehow? How do I resolve this?

EDIT: No, this is not a duplicate of that question. What OP is asking in his topic is how to account for lag visually from other players. The answer is mostly you can't, but you can smooth it out with entity interpolation.

My dilemma is that I can't figure out how to process inputs at all server-side using a fixed-timestep model. I assume the client sends timestamps which are processed when the server reaches that same frame, but if client+server are always frame synced, that means all messages are from the past and are ignored. If I allowed the server to accept a past input anyway it would have to implement it immediately instead of the original frame it was meant for, which would result in inaccuracy.

I'll make it real clear: If a client sends an input at tick 4 but it reaches the server at tick 7, how does the server go back and process an input meant for tick 4?


texts:
i have some doubts with multisampled textures.

In fragment shader, how to pass multiple samples?

We use glTexImage2DMultisample instead of glTeximage2D. so, how to upload texture data?

I want to use default FBO for this.


texts: How to generate arrays of item types knowing just the ratio of distribution

texts:
I'm stuck to find a good solution about spawning enemies. Think of it as a tower defense game.

What I'm trying to do is:

Create keypoints for enemy types and spawnrates, as

Wave0 = Enemy0 * 1.0
Wave5 = Enemy0 * 0.5 + Enemy1 * 0.5
Wave10 = Enemy1 * 0.5 + Enemy2 * 0.5

Interpolate these values and spawn enemies so that Wave3 would be Enemy0 * 0.7 + Enemy1 * 0.3

I'm trying to end up with a multidimensional array of int, representing enemy types and waves, such as;

EnemyWaves[0] = {0,0,0,0...} // array length = 20
EnemyWaves[3] = {0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0}
EnemyWaves[5] = {0,1,0,1,0,1...}
EnemyWaves[10] = {1,2,1,2,1,2,1...}


texts:
I'm having hard time converting OOP game objects to Ashley ECS framework. I have a character, gun & a bullet class. The character uses the gun as weapon, the gun class has a fire method that handles the creation of bullet. In the below code, is my current WeaponSystem that serves as a generic system for any weapon like Gun class.

public interface Weapon {
     void use();
}

public class WeaponComponent implements Component {
     Weapon weapon;
}

public class WeaponSystem extends IteratingSystem {

    ... // Constructor

    ... // Process Entity

    public void use(Entity weapon) {
         WeaponComponent weaponComponent = Components.getWeapon(weapon);
         weaponComponent.use();
         ...
    }

}

The character system..

public class CharacterSystem extends IteratingSytem {

    ... // Constuctor

    ... // Process Entity

    public void attack(Entity character) {
        getEngine().getSystem(WeaponSystem.class).use(character);
        // also can be use like this
        // CharacterComponent characterComponent = ...
        // it seems that, it was redundant
        // characterComponent.weapon.use();
    }

}

And the user controlled system ...

public class UserControlledSystem extends IteratingSystem {
     ...

     public void move(Entity character) {
          ... Set character directions

          InputComponent input ...
          input.key == arrow key, etc...

          getEngine().getSystem(CharacterSystem.class).move(character, direction);
     }

     public void attack(Entity character) {
          getEngine().getSystem(CharacterSystem.class).attack(character);
     }
}

Based on this article, they are using event dispatcher. But do I really need to use dispatcher? Is that possible to not to use dispatcher, just purely ECS? Anyways let's back to the main question(How to convert and handle (controlling) OOP game objects via ECS?). Currently, the Ashley ECS Entity has an access to engine and systems. Like in the above code example, do you think it is the proper way of handling the system?


texts: How to get the blocks seen by the player?

texts:
I'm writing a Minecraft-like game using Ogre engine and I have a problem. I must optimize my game, because when I try draw 10000 blocks, I have 2 FPS... So, I got the idea that blocks display of the plane and to hide the invisible blocks. But I have a problem - how do I know which blocks at a time are visible to the player?

And - if you know of other optimization methods for such a game, write what and how to use them in Ogre.


texts: When to use a blend tree vs state machine for animation

texts:
Im an experienced game dev hobbiest making my first game with 3d animated characters (in Unity) and am struggling to figure out when to use blend trees vs animation state machines. I understand both conceptually but have seen both blend trees and animation state machines used for character animation in a bunch of tutorials both from Unity and from other sources. I am not sure when / why one is better than the other am hoping someone can point me in the right direction.

My game is a 3rd person action rpg a'la WoW or KOTOR or Mass Effect (different systems I know but the perspectives and combat styles are kinda close at a high level). I have tons and tons of animations for attacks, blocks, feigns, deaths, walking, running, jumping, shooting etc but I am unclear on how to sequence them together naturally.

I have seen blend trees used for locomotion which makes sense to me when trying to keep character motion fluid, but I dont understand how to go from that blend tree to an attack state and nothing I have seen so far has gone past locomotion (no attacks etc). Do I need to make blend trees from my motion states to attack / death / dodge states? Do I have more control using just state machines? Im a little cautious of state machines because of the transition bloat that is so common with them and because I suspect there is greater potential for janky animation sequencing without blending.

I am planning to use the Unity character controller and write my own logic scripts to drive it. For the AI I will be using the built in nav mesh agents. Are character controller animations handled differently than the AI ones?

Any insights would be more than welcome!

Thanks


texts:
I have built a custom package for Unity called world-renderer. This is the folder structure.

Inside "Runtime" is all my source code. To use it inside a Unity project, I add this line into the manifest.json of that project.

"com.tamagames.extinction.word-renderer": "file:C:/Users/dbugger/projects/unity/world-renderer",

This has worked great so far, but now I want to start using ECS inside my custom package. so I add its namespace to one of the files:

using Unity.Entities;

and now when I return to the Unity Editor, I see the following error message:

  CS0234: The type or namespace name 'Entities' does not exist in the namespace 'Unity' (are you missing an assembly reference?)

I figured I needed to add the dependency to the package.json of my custom package, so I wrote updated it like this:

{
  "name": "com.tamagames.extinction.word-renderer",
  "version": "1.0.4",
  "displayName": "Extinction - World renderer",
  "description": "World renderer for Extinction",
  "unity": "2019.1",
  "unityRelease": "0b5",
  "keywords": [],
  "dependencies": {
    "com.unity.entities": "0.1.1-preview" // Dependency added
 },
  "author": {
    "name": "Enrique Moreno Tent",
    "email": "enriquemorenotent@gmail.com",
    "url": "https://enriquemorenotent.com"
  }
}

But I still keep getting the same error.

What am I doing wrong?

UPDATE

I try adding the reference to the Assembly of my package, like this:

{
    "name": "Unity.com.tamagames.extinction.world-renderer-ecs",
    "optionalUnityReferences": ["com.unity.entities"],
    "includePlatforms": [],
    "excludePlatforms": [],
    "allowUnsafeCode": false,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": [],
    "versionDefines": []
}

That did solve the problem with "Unity.Entities" not found, but now, in the Unity Project, the classes inside my source code cannot be found!


texts: Invalid operation (1282) in GLSL vertex shader

texts:
My GLSL vertex shader works fine, but you if put a for loop inside or rename the uniform xxx to something else, it says the follwoing:

Exception in thread "main" org.lwjgl.opengl.OpenGLException: Invalid operation (1282)
    at org.lwjgl.opengl.Util.checkGLError(Util.java:59)
    at org.lwjgl.opengl.GL20.glGetUniformLocation(GL20.java:664)

this is the method causing the problem:

protected void getAllUniformLocations()
    {

        location_transformationMatrix   = super.getUniformLocation("transformationMatrix");
        location_diffuseColor           = super.getUniformLocation("in_color");
        location_projectionMatrix       = super.getUniformLocation("projectionMatrix");
        location_lightPos               = super.getUniformLocation("lightPosition");
        location_lightColor             = super.getUniformLocation("lightColor");
        location_viewMatrix             = super.getUniformLocation("viewMatrix");
        location_specular               = super.getUniformLocation("specularLevel");
        location_boneTransformations    = new int[32];
        for(int i = 0; i < location_boneTransformations.length; i++)
            location_boneTransformations[i] = super.getUniformLocation("xxx["+i+"]");
    }

this is my vertex shader:

#version 400 core

//data from VBO
in vec3 position;
in vec2 texture_coordinates;
in vec3 normal;
//bone data
in int bone_pointer;
in float bone_intensity;
//vertex color output
out vec4 color;
//texture coordinates
out vec2 pass_texcoords;
out vec2 texCoord0;
//normal
out vec3 surface_normal;
//vector pointing towards the light
out vec3 to_light_vector;

//position, rotation, scale
uniform mat4 transformationMatrix;
//perspective projection
uniform mat4 projectionMatrix;
//TODO: material color
uniform vec3 in_color;
//camera viewmatrix
uniform mat4 viewMatrix;
//lights
uniform vec3 lightPosition;
uniform vec3 lightColor;
//skeleton data xxx = bone transformations
uniform mat4 xxx[];
uniform int group_indices[];
uniform float group_values[];
void main()
{
    for(int i = 0; i < group_indices.length(); i++)
    {

    }
    mat4 total_transform =  transformationMatrix;
    total_transform = total_transform * xxx[0];

    vec4 worldPosition;

    worldPosition =  total_transform * (vec4(position, 1)) ; //

    vec4 pos =  projectionMatrix * viewMatrix * worldPosition;
    gl_Position = pos;

    //Texture
    pass_texcoords = texture_coordinates;

    //light
    surface_normal = (total_transform *  vec4(normal, 0)).xyz;
    to_light_vector = lightPosition * worldPosition.xyz;

    //textures
     texCoord0 = texture_coordinates;

}


texts:
I'm having a problem with rotating a Shape in Slick2D for Java

I have a code in screen render which works properly:

Shape box = new Rectangle(100,100,32,32);
    box = box.transform( Transform.createRotateTransform(1f,116,116));
    gfx.draw(box);

public Entity(int x,int y,int sheet,Shape collisionbox1){
    sheetIndex = sheet;
    sheetX=0;
    sheetY=0;
    rotation =0f;
    position = new Vector2f(x,y);
    this.collisionBox = collisionbox1;
} // entity inallization

map1.entity_list.add(new Entity(100, 100 , 0,new Rectangle(100,100,32,32))); // thats where i add entity into my map

public void render(GameContainer game, StateBasedGame state, Graphics gfx)
{    Image img =Start.theContent.SheetsList.get(sheetIndex).getSprite(sheetX, sheetY);
    img.setRotation(rotation);
    img.draw(position.x-Start.theGame.camera.x, position.y-Start.theGame.camera.y);
    gfx.draw(this.getBounds());
} // thats where i render entity (camera.x = 0 camera.y =0)

public boolean update(GameContainer game,StateBasedGame state,int delta) {
    rotation +=1f;
    if(rotation >360)rotation -=360;
    if(rotation < 0)rotation += 360;
    collisionBox = collisionBox.transform(Transform.createRotateTransform(1f,116,116));
    return true;
} // here is where i routate the entity collisionBox = Rect{100,100,32,32} so center should be 116 116

When I start the program I get random moving & rotating rectangle on the screen.

When I check its x,y,and center it writes 0,0 and a random center. For example:

0,0 116.000046,115.99997
0,0 0.0 0.0 116.00006 116.00001

Its really strange to me. Sorry for the bad explanation; if you need to know anything else about my code, please tell me.


texts:
Sorry if my title was not clear. My script needs to fix the method of movement object. In my script, the Z axis angel of main object moves with the target object on Y axis. If target goes under zero value, main object goes back smoothly. But, if target goes up from "part 2 to part 1"...it just be there.I don't know how to invert or reverse the movement. Here is my script

public Transform target;
public float dis, zz;

// Update is called once per frame
void Update()
{
    dis = transform.position.y - target.transform.position.y;
    transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, zz);
        // part 1
    if (dis < 0.0f && dis > -0.3f)
    {
        zz -= Time.deltaTime * 0.2f;
        if (zz <= -0.3f)
        {
            zz = -0.3f;
        }
    }
        // part 2
    if (dis < 0.31f && dis > -0.6f)
    {
        zz -= Time.deltaTime * 0.2f;
        if (zz <= -0.6f)
        {
            zz = -0.6f;
        }
    }
        // part 3
    if (dis < 0.61f && dis > -0.9f)
    {
        zz -= Time.deltaTime * 0.2f;
        if (zz <= -0.9f)
        {
            zz = -0.9f;
        }
    }

}


texts: Facebook SDK Error 'graph_domain' not found

texts:
using Facebook Unity SDK v7.19.0 with FBAndroidSDK/6.2.0

I am receiving a Log Warning

Did not find expected value 'graph_domain' in dictionary

What does this means? and how to handle it so that I can remove this warning.


texts: Arbitrary projection matrix from 6 arbitrary frustum planes

texts:
A projection matrix represent a tranformation from the camera view space to the rendering system clip space. In other words, it defines the transormation between a 6-sided frustum to the clip cube.

The glOrtho and glFrustum use only 6 parameter to define such a projection, but impose several constraints on the frustum that will get projected to the clip cube: the near and far planes are parallel, the left and right planes intersect on a vertical line, and the top and bottom planes intersect on a horizontal lines, both lines being parallel to the near and far planes.

I'd like to lift these restrictions. So, from the definition of the 6 frustum side planes (in whatever representation you see fit), how can I compute a general projection matrix?


texts: How can I support both multiple resolutions and multiple orientations in a game?

texts:
I am writing a mobile Android and iOS game.  This game is similar to Doodle Jump, but without scrolling.  In my game I display a background image that should cover the entire screen.  On top of that I draw some 32x32 tile images that make up the platforms.  I have three control buttons that are displayed at the bottom of the screen. The score is displayed at the top of the screen.

I am trying to ensure that this game will work on any resolution and can be rotated from landscape to portrait mode and vice versa. The player should be able to change orientations without losing sight of any platforms.

I have found several methods for doing this, however they only seem to work if you lock the orientation or skew the images.

Scaling the content
Won't work because it will skew images too much and look unprofessional.
Scaling the content and keeping the aspect ratio via letterboxing
The black bars that this introduces can become overwhelming.  For example, if I rotate a 960x640 resolution device to portrait, the new resolution will be 640x960.  When I tried implementing this, it gave me horrible results.

Portrait:

Landscape:

Scaling the x,y axis with separate values

scaling factor (on x-axis) = screen width in pixels / target width in pixels
scaling factor (on y-axis) = screen height in pixels / target height in pixels

This method changes the bounds of the coordinate system, which I am trying to avoid.
Using a virtual viewport
I like this idea, however it still doesn't seem to work with orientation changes.  The variation of aspect ratios seems to be to large when you try this approach for landscape and portrait.

Some good links I found on the topic can be found here
http://blog.gemserk.com/2013/01/22/our-solution-to-handle-multiple-screen-sizes-in-android-part-one/
http://v-play.net/doc/vplay-different-screen-sizes/#approaches-for-content-scaling

I have also thought about only stretching the background image and recalculating the new positions for everything else (player and platforms) when the orientation changes.  However, I'm not sure how this would affect collision detection and jumping in real-time.  I would rather solve this with a different technique if possible.

It seems like most people just lock their game in one orientation.  I am trying to avoid this, if possible.

The bottom line is that all of the methods I listed look to only solve the resolution issue if you lock the orientation.  Is there a way I can support both orientations?


texts:
I am working on a personal project and am trying to make a 2d tile map render that needs to handle rotation.

I am using raylib to handle the drawing stuff onto the screen and am using this function to draw a tile:

void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, Vector2 origin, float rotation, Color tint);

How do I calculate the new coordinates of the tiles after the rotation and the individual rotation of each tile if I want to rotate the tile map?

I also need to figure how to do mouse click detection for tiles when they are rotated with their new coordinates and how to do ‘collision detection with cursor’ with rotated squares/tiles.

And due to the way the project is set up I cannot rotate the camera.

Extra info/diagram:


texts:
I have a box (non-rectangular cuboid?) and would like to convert it to a matrix such that when a point inside the box is multiplied by the matrix, a vector is returned that describes the relative position inside the box (very similar in regard to a camera's view and projection matrix)

The difference between this box and a camera frustum, is that the box vertices are defined by the points intersecting 4 rays from the center of two concentric spheres.

What's the formula for creating such a matrix?


texts: How to make Sword disable when I walk into different scene

texts: So I have a sword animation and it attacks enemies and stuff but whenever I walk into a house scene I want it to disable. So it only is enabled in outdoors scenes


texts:
Before I start making a game, I'm trying to figure out how I will manage things.  One of the first things I'm not sure about is how to manage entities (enemy, player, projectile...)

I'm going to be using either C, C++, Java, or C#

One of the ideas I have is to use one array for projectiles and one for enemies.  Each time I have a new entity, I grow my array. Here is the problem: If player/enemy is firing, that creates a new entity which means the projectile array is growing.

Suppose its projectile #2053, when it hit something, I free it, then in my loop to check which projectiles are to do something, like getting closer to there target, I check if every # of my array to see if its null, if not, check is trajectory. But the problem is that the array will grow each time a new projectile is fired, and I will get a memory problem at the end.

So how should I manage my entities?

I need an awnser that covers both object oriented and procedural, since I mainly do things in C.


texts:
I am working on Unity 5.4. I have an Event System, my UI has a parent canvas, Canvas has the graphic raycaster. I am not able to understand why this is not working. I have attached an image of the button script, Canvas, event system and my script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Level01Controller : MonoBehaviour
{
    private int highScore ;

    void Update ()
    {
        if (Input.GetKey (KeyCode.Escape))
        {
            Application.Quit ();
            Debug.Log ("Clicked);
        }
    }

    public void StartGame()
    {
        Application.LoadLevel ("Level01_Game");
    }
}


texts: Algorithm to reduce a bitmap mask to a list of rectangles?

texts:
Before I go spend an afternoon writing this myself, I thought I'd ask if there was an implementation already available --even just as a reference. The first image is an example of a bitmap mask that I would like to turn into a list of rectangles. A bad algorithm would return every set pixel as a 1x1 rectangle. A good algorithm would look like the second image, where it returns the coordinates of the orange and red rectangles. The fact that the rectangles overlap don't matter, just that there are only two returned.

To summarize, the ideal result would be these two rectangles (x, y, w, h): [ { 3, 1, 2, 6 }, { 1, 3, 6, 2 } ]


texts: Maintaining frame rate while using many High Resolution models

texts:
I have shelves "made of" steel rods as a 3D-file. So a lot of virtual metal rods make up a cage. When cloning this in unity a few times even my fast computer can only show this in a choppy way. But using an opacity map yields a flat result, which I don't want. For realism purposes there should be cylinders or similar, i.e. real 3D objects or the impression of real 3D objects, at least in close range.

How could I do that with more shelves without making the frame rate drop considerately?

I found that even though I am using opacity maps(128 x 128) just ten shelves and even 3dsmax begins stuttering.

EDIT: I uploaded a demo, it's for Win, X86 and X64. Get it here: http://www.sockshare.com/file/08BD739BDF94601C You need the opensource 7zip to extract.


texts: unity game engine - should I be using a di framework / ioc container

texts:
Is it worthwhile for a solo dev to take up the widely recommended practice of using a dependency injection framework within the unity game engine? I have seen reason for concern regarding the clash of development methodologies that seems to have put some people off. If you would recommend against the practice, what would be a better substitute to avoid rigid bindings and singletons.

The focus of this question is primarily on the supposed clash with the unity way of things, which has apparently made a lot of people feel like they are spending more of their time fighting their tools instead of making games. I don't want to spend all my time worrying about nice code and have no game at the end of it, so advice and answers are appreciated.

So far my thinking is that it might be worthwhile for larger projects/ long term projects or projects with a team of more than a few people, but for small projects, time limited projects and indie/hobbyist projects its probably not a worthwhile investment of effort. Instead so far I'm thinking a minimum of tdd but then whatever you feel comfortable with, trying to maintain some of the most important principles in programming, such as yagni, kiss and srp. I watched a talk by johnathon blow where he essentially says to keep things simple and don't overthink them.

Am I mistaken in my assesment? Am I attributing more effort to working with di frameworks than is fair? Is it skewed by my inexperience? If you work with di and you find it actually speeds up your workflow while at the same time gaining the advantages di offers, please leave a comment or answer as you are someone I would love to hear from.


texts:
http://dev.windowsphone.com/en-us/downloadsdk

I downloaded the current version of Visual Studio to develop Windows Phone apps, but I don't know how to add XNA. I tried to install XNA, but it's not working with Visual Studio.

How can I use XNA with Visual Studio Express 2013 for Windows?


texts: How can I give a MonoBehaviour field a default value that depends on the object?

texts:
In Unity3D, I have a MonoBehaviour which gets added to game objects. I'm adding a string "name" field to it. I'd like the default value for the name to be the name of the game object the component is added to. Is there an easy way to do this? Some more details:

The component is an existing one to which I'm adding the name field. In old versions, the name was always the name of the game object, and this is a new feature to allow them to be different.
The common case is (still) for the name to be the name of the game object, so having that as the default would simplify the process of adding the component to a new object.
Ideally, deserializing an old scene will fill in the default, so updating scenes takes zero effort. I'm less concerned about this than about newly created scenes/objects.
The component already uses a CustomEditor.
I don't care about updating the name in the component if the game object's name is changed, or if the component values are pasted into a different game object.

One way I can think of is to add a bool "override name" to the object. If the bool is unchecked, it uses the default name (the game object); if it's checked, it uses the new field. But I'd like to avoid adding complexity to the GUI to support it. The whole point of my request is to add the new functionality (overriding the name) without adding steps to the creation workflow.


texts: How to detect a cursor inside a non-rectangle shape

texts: How can I detect and do something if the cursor is inside a hexagonal shape? Is there any way other than detecting if it's in a rectangle area close to the shape of the hexagon? It would also have to work with a grid of hexagons, detecting each individually.


texts: Reducing APK File Size by using JPG instead of PNG for game background images

texts:
I've just finished my (openGL ES 2.0 Android) game and it's almost ready for Alpha-testing.

When I export the application to an APK File, the file is taking up 16MB and I would like to reduce this as much as I can.

Here are some points about what the project contains and what I've tried to reduce the size already:

222kb of Ogg Vorbis files used for Sound Effects
1 x MP3 file at 5.59MB (128kbps Bitrate)
4 x sets of PNG files used for textures (XHDPI, HDPI, MDPI & LDPI - I'm not using XXHDPI)
Just over 1MB of code

What I've tried thus far to get where I am:

I've optimised the PNG files using Optiping
I've applied ProGuard to my code before exporting, this didn't really help by much as 99% of my app is resources.

So my question is, is there really much else I can do to reduce the size of the APK?  I was thinking about maybe using JPG format source files for my Background OpenGL textures instead of PNG - anyone have any experience with this?  Does it hurt performance at all?  I can see that it would make quite a difference - my atlas of backgrounds in PNG format for XHDPI is 1.7MB - and a 90% compressed JPG comes in at around 650KB.  I'm just not sure if it's a good idea as everyone always advocates PNG > JPG.

Any pointers from personal experience would be helpful & also if I've overlooked anything other than using JPG's.


texts: It seems like creating a bunch of rigid bodies (say 100K) causes a huge slowdown. However, what if the model the rigid body is attached to isn't visible. Is there a way to remove the rigid body from any sort of iteration from Newton so it doesn't cause a slowdown during run-time?


texts: A ball hits the corner, where will it deflect?

texts: I need to brush up my trigonometry and hope you can help here with a simple mathematical model. Here is my model so far in the image attached. I am aware that the frame animation has other problems when the ball is moving very fast, but for now I just need to calculate ballDx and ballDy. It is also possible that ballDx = 0 (vertical movement only), but when the ball deflects ballDx may get a different value.


texts: How to align a hint arrow to point along a path?

texts:
I am using CalculatePath and trying to use path.corners in order to give user a hint for path, that where should he lead next. I am using first two instances of Vector3 of path.corners. Lets call those vectors A and B. Let me illustrate this using figure.

Now I want to position my arrow above the midpoint of the line from B to A, and orient it so it's pointing along the direction from B to A.

When I orient the arrow with LookAt(), it doesn't point in the same direction as the path. Here is an image of my arrow prefab, showing how it's oriented:


texts: Textures go black when changing Quality Settings at runtime

texts:
Whenever I change my Quality Settings at runtime in editor mode or in build, all of my textures turn black. I use the following line to change the quality settings :

QualitySettings.SetQualityLevel(value, true);

I have tried to set the boolean at false and it does the same result. I am using HDRP and the shader "HDRenderPipeline/Lit" on pretty much all of my materials. There is an interesting fact, in editor mode, I just hover my mouse on any material inspector window, it updates all of my textures back to normal and solves the problem.
Here is a screen showing the textures (left is normal, and right is bugged):

Any idea ? Thanks.


texts: Take an image and cut it up into a tile map

texts:
So I am attemping to make a game in Phaser.

I am trying to think of the best way to cut this image up and make it in to a tile map OR do I try and lay this entire image as a back ground to the game and just determine where the mouse was clicked.

I believe the images have a width of 140 and a height of 160 or 162.  Then I would have to make the four corners of the image transparent so I can overlay them to create the map.

If I want to go with a scrollable background, I am not sure how to proceed, would I overlay hot spots on to the screen and would I have to do a point to hex conversion as I would not have the tile coordinates


texts: 2D Platform physics system with deltaTime

texts:
I'm implementing my physics handler in my own 2D "Platform" game.
My main problem is that when the timestep ( deltaTime ) changes, maybe to some tiny lag spike or something like that, the running entity visibly changes its speed ( running at top speed, actually) and that is really annoying to see. Other than that, if my game run slower (for example at ~33 fps) the entity moves definitely slower, which is, of course, not good at all, and moves 'lagging', in a completely not smooth way.
I use a variable time step and I limit FPS only if I have to do some test (for example simulating lag).
The game, and so the timestep calculation, is made with C++ and SDL2 but I think this issue is not language-specific. By the way this is how I calculate the timestep:

double last=0, delay=0;
while (running) {
    Uint32 now = SDL_GetTicks();
    if (now > last) {
        delay=now-last;
        last=now;
    }
    view->update(delay); // This is where every game logic takes place
    //... Do other stuff (clear screen, clear inputs, swap buffers)
}

Generally, this code works just fine, if my fps are less, then the deltaTime (delay in the code) increases. And that's ok. On the other hand there is a huge problem which is, of course, affecting my physic system: if my game runs faster than a certain number of fps (i.e. fps >= 1000 ) then, not matter what is the specific value, delay is always 1.
This makes a game session running at 1000 fps fast 1/2 of a session running at 2000fps. I know those values are extremely high and that my game is running like that just because now it's empty, but I think I can't ignore this problem. What if a super high extreme gaming machine tries to run my game ?

Now let's talk about physics:
My physics engine is really simple. It is 2D and, for now, I implemented only the x-Axis algorithm. My entity has a 2D vector holding speed (speed.x and speed.y ), a top speed (maxSpeed) and, of course, a position).

My engine works like this:

//Code executed in every frame:
if (fabs(speed.x) > 0 ) {
    speed.x /=  delta; //Simulate a very high friction

    if (fabs(speed.x) > maxSpeed) { //check if exceed the top speed
        //if so, set the speed to the top speed with the same sign
        speed.x = (maxSpeed * delta) * sgn(speed.x);
    }

   //Finally change the position according to the speed
    x += speed.x*delta;
}

That is what I use to simulate a physic system, where sgn is custom function which returns 1 if the value is positive, -1 otherwise. I know the friction is very high, but at the moment I do not care too much.

The last piece of code I use, is the code to make the entity actually move. To do so I use this piece of code:

if (input->isKeyDown(KEY_D))
    speed.x += acceleration.x * delta;
else if (input->isKeyDown(KEY_A))
    speed.x -= acceleration.x*delta;

In this code acceleration is like a constant, it's simply a value.
Now the code works fine in very general terms but the problems are:

Even a little change to delta (delay, variable time step) makes the entity visibly change his own speed (I guess it's related to top speed).
If my game runs on average of 30 -- 45 fps, the entity moves, but at a different top speed and the transition is verry laggy.
At a certain point delta becomes constant and that breaks up every physic logic.

I think everything is related to how I use my delta (delay) in each frane


texts:
I would like the game to give all 16 characters (15 NPC + 1 player) a number: 1-16. This number stays the same no matter what and is unique only to that character so two characters cannot have the same number. At a point in the game, the character presses a button.

I need this button to generate a random number and load a scene based on the number. Example: Player's pre-determined number is "8", if the number generator generates an "8" as well, it would load the next scene (where the player has to run away from a mob) If the generator generates anything else other than "8" It will load a different scene (where the player chases an NPC)

Just to clear it up if the number generator generates 1-7 or 9-16 it will load the same scene no matter what. (Getting "9" from the generator would load the same scene as "2" would. Only when "8" is generated, would there be a separate scene)

I'm still incredibly new to Unity and coding in general, so a brief summary of what each line of code is doing would be majorly appreciated! (but not at all demanded!)

I'm most comfortable with C# so if you could have the code in that would be great!


texts: Box2d: crash on createBody in beginContact callback

texts:
I am getting this error on creating body in contactListener

com.patchnhack.gdx A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x58 in tid 4628 (GLThread 15500), pid 4583

I am creating a body in beginContact callback like this:

    ......
    public void beginContact(Contact contact) {
        .....
        Fixture fixA = contact.getFixtureA();
        Fixture fixB = contact.getFixtureB();

        If( fixA.getUserData()== "ground" || fixB.getUserData()== "ground")
            createBody(0,0);
        ....
        ....
    }

// createbody method in screen class
    public void createBody(float x, float y, float radius) {
        BodyDef def = new BodyDef();
        def.type = BodyDef.BodyType.DynamicBody;
        def.position.set(x ,y);
        def.fixedRotation = true;
        body = world.createBody(def);
        CircleShape shape = new CircleShape();
        shape.setRadius(radius);
        FixtureDef fdef = new FixtureDef();
        fdef.restitution = 0.5f;
        fdef.shape = shape;
        fdef.density = 2;
        body.createFixture(fdef).setUserData("chip");
    }

I know this is something due to async with render thread. Please tell me how can I resolve this or some better way to do this.

edit: I have even tried

Gdx.app.PostRunnble(new Runnable(){
..
})

But that works strangely and bodies keep populating and ultimately crashing the app.


texts: I get this error when I'm trying to play a sound in XNA: Error  1   Audio file cash-register.wav contains non-PCM data. What is PCM data?


texts: How to randomly spawn a Rect on x position (android studio)?

texts:
I want to draw a rect with a 50x50 size, however I want it to appear randomly on the x position. Where should i set the x position?

This is how i set my rectangle.

rectangle.set(50, 50, 100, 100);

I've done several changes on this setting the but I can't figure it out.


texts:
I am thinking about making a simulator type game that will involve having lots of small objects in a 3D space.  What is the typical solution for handling these objects?  The first thing that comes to mind is a 3D Array, but I can't help but think there is a more efficient solution.  Another idea that comes to mind is objects having possession of smaller items. For example a House possesses a Table which possesses a Cup and Bowl.

The final way I can think of handling this is just having an array of "objects" that each have an x, y, z value.  While this would make storing them easy I do not understand how you would detect collisions without just looking at every possible object and checking to see if it is in the way.

Are there other ways of holding onto these objects that is more efficient?

Edit: Following up with the comments below, are there typical thread-safe ways of implementing these structures in Java?


texts: How can I calculate all the tiles visible to a camera in 2D?

texts:
I am creating a basic tile-based 2D game ~mostly from scratch in Java, however all I need is pseudo-code for how this could be achieved.  My problem lies in the fact that my world (stored in a HashMap so I don't have to have a null object for every position down to 0) maybe millions or even billions of tiles large, so I'm sure it is not efficient to loop through every tile.

A solution I have thought of to solve this issue would be to try to calculate based on the position of the camera in the world and the size of the tiles how many could fit on the screen in the X and Y axes, and also the offset of them to the screen as well, but I have tried (and failed) to implement this, because I am unsure on how to convert this is Maths/Logic.

How may I go about this?  Below I have linked an image showing what tiles I intend to show to the screen, where the black square is the centre and tiles that do not cover the screen are not shown.


texts: Mixamo: can animations ("without skin") be re-used on any Mixamo rigged model?

texts:
I've discovered Mixamo very recently. I plan to use its auto-rigging capability on all my unrigged characters.

The download option can either include the skin or just obtain the animation.

My understanding is that an animation is "simply" applying a composite timeline where each bone is modified separately.

Am I right to believe that downloading an animation from Mixamo makes it compatible with every Mixam-rigged character? Or am I to download the same animations for each variation in my skeletons (arm length, hip width, neck size, etc.) ?

Quick heads up: Mixamo

Mixamo is an auto-rigging tool. For instance, this Blender character will be imported as a .zip (containing my .obj and .mtl)

You are just expected to place the following colored circles on your humanoid:

After the auto-rigging completes, you can either download your static, rigged character (as an .fbx) or animate it using one of the many free animations. After applying an animation (one at a time), you can either download the character (mesh) plus its anim or simply the bare skeletal animation.

Thanks!


texts: Acceleration and Deceleration During Rotation

texts:
I'm attempting to have a sprite rotate in a way where its rotation speed increases until it has reached the halfway point in its rotation, to which it starts to slow down. I'm currently calculating the halfway point by calculating the amount of time it should take to rotate the sprite, and then checking if a current time variable is larger.

The code works rather well except for the fact that I can't figure out how current time should increment each update. Currently I'm using delta time, but that doesn't work. I'm thinking it needs to be some combination of the calculated time to rotate and delta, but I haven't gotten it yet (clearly).

EDIT:
Specifically, currentTime shouldn't be incremented by delta solely, but I have no idea what it should be in place of delta.

        if (currentTime <= timeToRotate)
        {
            rotationSpeed += 5f * delta;
            currentTime += delta;
        }

        else
        {
            if (rotationSpeed > 5f)
                rotationSpeed -= 5f * delta;

            else
                rotationSpeed = 5f;

            currentTime += delta;
        }


texts:
How do you create a random grid where the lines aren't orthogonal (and cells aren't a perfect square), but are warped?
Here's an example of what I mean:

(Credit: screenshot taken from a video by Silvarret about the game Townscaper.)
Lines curve. Sometimes many cells come together in a single point. Yet, it still looks like a grid and the cells are clearly visible and roughly equal in size and shape.
I have absolutely no clue how to go about something like this. How is this achieved? Is there an algorithm for this? How would you detect the cell over which the mouse hovers?


texts: Having trouble setting color in fragment shader

texts:
For some reason, the color isn't applying to the object. Here's my fragment shader code. There's probably something obvious wrong with it that i'm not seeing.

#version 330 core
out vec3 Color;

uniform int InColor;

void main()
{
        Color = vec3(float(127 / 255), 0, 0);
}


texts: How do I determine distance of a point within a ProBuilder mesh?

texts:
As in the title, I have an effect prepped for my game which applies certain derived parameters to a post-processing effect after the player enters a boundary I created with ProBuilder. Finding how far inside the bound the player is; that is, how far the player would have to travel, at minimum, to leave it; would help me scale this effect. It is not an axis-aligned boundary, and its sloped shape is fairly important. Having the effect go full-on on crossing the boundary would be jarring to the player.

I'm tempted to resort to traditional edge testing with this, but I would like to highlight that it will be done at least once per frame on multiple objects, so I would like to keep it as simple, and non-home-rolled, as possible.

The other possibility would be to keep track of time exposed and scale it by that; but this isn't ideal and I'm seriously curious as to whether a penetration-depth-testing method exists out-of-box.

A requested image of my setup:

It is laterally symmetric, and that is unlikely to ever need to change. However, future volumes are likely to have varying angles and heights. Depth is more-or-less irrelevant, as while I'm using 3D, this game has the physics of a 2D platformer; so you can consider it to have infinite depth if you need to. As you can see on the right, I've added almost nothing to it, other than the MagneticField.cs custom script (which does not even reference the mesh, only whether it's been crossed) and a debug class, TriangleReport.cs, that I'm working on right now.

One thought I had was to get triangles for the top, bottom, left, and right edges, use them to define planes, and then determine the distance from those planes; but if you've got something better I am all ears!


texts: Arrow key control on winforms RichTextBox

texts:
I am making a faux console using winforms for the game I am working on. Right now I am moving a '0' across the screen using the arrow keys.

In order to provide fine grain formatting on the text, I am using a richTextBox for the console display. The background for this box is black.

Problem: If the richTextBox is set to Enabled = false I can use the arrow keys without a problem but the box background color is grey and will not change. If I set it to read-only, when using the arrow keys it will just move the cursor and my arrow key events will not fire.

I am fine with setting the text to read-only and getting my black control color. So my question would be, is there a way to set the control to read-only and still allow for my arrow key events (and not move the cursor)?


texts:
While I am slowly learning how to build an android game, I would like to build images for a game, especially texture atlas.

But the only image handling system I am familiar with is Photoshop. And I am not sure it is a good tool to organize images and to get coordinates for game dev.

Is there any good tool for this purpose? If photoshop is still good for this, any reference to show how to do it would be appreciated.

UPDATE: the second question was answered by this But still want to hear more options.

UPDATE2: In case you are using libgdx, I found it does the packing for you.


texts: Does a detailed texture take longer to render?

texts:
Let's say I want to render a square; its texture is "square.png."

Is it easier for the computer to render it if the texture is just a plain color?

And what about if it is a very noisy texture with completely random colors here and there?

Or what if that texture is noisy in the sense that every pixel in it is different from one to another, but only by a tiny bit?


texts:
I would like to have a Main Controller class that should exist in many scenes.
I used DontDestroyOnLoad and in runtime an object associated with this class is present in hierarchy. However, how can I use this script if its only visible in runtime? How can I assign the coresponding game object to button if I cant see It until I run the game?


texts: How to reset an incremental achievement in Googles Android API?

texts:
For example the achievement is "Pass 5 levels in a row without failing"

It's incremental and has five steps.

If a user hits an obstacle, this achievements score should obviously be resetted to 0.

How to to this? I found no such method or anything in the internet.


texts:
I'm currently in the process of making a 3d "semi" top down game, the camera comes in at a very high angle near 90 to show off the 3d models. I have a main character which can move in 4 axis (up, down, left right) using the arrow keys. I'm trying to create a smooth rotation between each of the axis so that when you press right when the character faces up, his rotation just doesn't jump.

Rotations seem to be weird and I don't quite understand why MathHelper.ConvertToDegrees or Radians doesn't quite give me what I want. When I try to rotate the model, I am translating it back to the origin, rotating then translating back for my order of matrices.

Although what I've found is that for rotation in the Z-axis, 0f seems to be down, 1.6f seems to be right, 3.2f seems to be up and 4.8f seems to be left. So to translate smoothly what I do is say I'm facing up (3.2f) and I want to face, right: Rotation.Z > 1.6 so, while it's greater keep subtracting 0.08f until we reach 1.6 or lower. This works well.

BUT my problem lies in since down is 0 and left is 4.8, when you're facing left and want to face down, you rotate clockwise all the way back to down instead of the logical counter-clockwise. This only happens in left to down or vice versa.

I've thought long and hard about this, down can also be expressed by 5.4f I assume but that doesn't really solve my problem. The approach for going down looks like this:

    else if (currentKeyState.IsKeyDown(Keys.Down))
    {
        //Rotate character to face this direction
        if (rotation.Z != 0)
        {
            if (rotation.Z < 0)
            {
                rotation.Z += 0.08f;
            }
            else if((rotation.Z > 0))
            {
                rotation.Z -= 0.08f;
            }
        }

Since for the left rotation, the rotation.Z value will be 4.8, then by this logic it'll going counter-clockwise. It's probably a simple solution but it has me stumped and one of my biggest problems is not moving on until a problem is fixed even if the game still works.

I've attached a picture of the axis just in case my post is nonsensical:

Look forward to any potential solutions.


texts: How do you allow joints in a character to fall freely based on gravity?

texts: I am building a game in Unity in which a character falls down on death. Is it possible to make the joints fall and bend based on gravity? That is to leave the joints fully dependent on gravity and colliders and not any skeletal animation.


texts: Tile based isometric depth sorting on different size objects.

texts:
I am creating a tile based isometric game.

The problem we are having is with depth sorting, we tried a lot of methods but none work.

They all do a great job but its not perfect, they seem to bug sometimes.

We have tiled objects of different sizes, like 2x2, 2x6, 3x4. This makes it so hard.

We are trying to avoid slicing the bitmaps.

Anyone has a idea?


texts:
My game is not grid-based, so units can be at any arbitrary coordinate and move at different speeds. My obstacles are all rectangular and axis-aligned, so naturally it makes sense for me to overlay a grid over the map for pathfinding. Each unit will take up a grid cell (floor(unit.x / CELL_SIZE), floor(unit.y / CELL_SIZE)). I will then run standard A* grid-based pathfinding on the grid.
The problem is that although the path is grid-aligned, the unit movement is not. Thus, in the midst of moving, the unit might end up colliding with a cell that is blocked, and get stucked. Here's a picture to illustrate:

I'm trying to get from point A to point B. B is the center of the grid cell, since it is a waypoint from the found path. A is the point the unit is currently at. The pathfinder thinks A to B is valid movement, since it takes the grid cell of A as the start point and the diagonal neighbour B is not blocked. But moving from A to B might result in position C, which is blocked.
I thought of using a soft collision radius for pathfinding, but it has its problems. The pathfinder will not return any paths where there's a soft collision. So if the current location of the unit already has a soft collision, the unit cannot move! It seems that it is necessary to keep the pathfinding collision and physics collision identical...
How do I resolve this problem, and what is the standard way to overlay a grid for pathfinding?


texts: How do I scale a Spine animation at runtime?

texts:
The spine docummentation shows how to scale the skeleton when loading.
Is it a must to reload the skeleton to scale the animation while playing it?


texts: How to simulate organs as damage boxes in unity?

texts:
I am making a Battlefield simulation game similar the the VBS series and ARMA, and I am wondering if there is a way to accurately determine realistic damage of player characters using damage boxes.

i am taking after warthunder in the the only thing that becomes damaged is whatever is hit. I aim to do a similar system with player characters and NPCs


texts: vuforia how do I force objects into a 2D plane

texts:
I'm working on a game in which cards are placed on a table and then rendered in augmented reality. These objects have 3D physics attached to them which doesn't work as well if they are either rotated or if the system mistakes them for being higher or lower then they really are.

Is there a good method to force Vuforia/Unity to place all items in the same 2D plane and keep all of them upright compared to that plane?

I currently have the following code:

using UnityEngine;
using System.Collections;

public class projectioncode : MonoBehaviour {
    Vector3 p1;
    Vector3 p2;
    Vector3 p3;
    Vector3 v1;
    Vector3 v2;
    Vector3 normal;

    /*
     *use a plane with the following 3 coordinates
     */
    public void setPlaneByPoints(Vector3 point1,Vector3 point2, Vector3 point3){
        p1 = point1;
        p2 = point2;
        p3 = point3;

        v1=p2-p1;
        v2=p3-p1;
        normal=getNormal(v1,v2);
    }

    public Transform projectTransform(Transform input){
        input.position = projectPoint (input.position);
        return input;
    }
    /*
     *  projects a 3d point into space;
     */
    Vector3 projectPoint(Vector3 point){
        Vector3 vOToPoint = point - p1;//vector between origin and point
        float dist = Vector3.Dot (vOToPoint, normal); //distance plane to point
        return point - dist * normal;
    }

    /*
     * caclulates the normal of 2 vectors
     */
    Vector3 getNormal(Vector3 v1,Vector3 v2){
        Vector3 res= (Vector3.Cross (v1, v2));
        res.Normalize();
        return res;
    }
}

This seems to project objects onto a plane but the results tend to be inaccurate and result in weird movements, particularly when moving the camera around.

This is what it looks like:


texts: Other displacement/deformation methods than vertex displacement?

texts:
Using vertex displacement on low-res models lead to artifacts, and I imagine tessellation might be a bit slow, if I want it pixel-perfect.
I know signed distance fields can be used, though I doubt that's fast either.
Are there any other approaches? Is using tessellation fast enough for a large scene with hundreds of constantly deforming objects?


texts: Is A* suitable for this particular case?

texts:
I have a 2D map of nodes a train could travel. They are not in a grid. The node positions are placed by a designer and exported to a JSON file which the game loads to display the node positions on the map texture/sprite.

I'm tying to implement pathfinding for the train. The user can select a node and set a waypoint to that node. The game should find the shortest path and take that (avoiding locked nodes).

The way the nodes are set up right now is that each node has other neighbour nodes. There's the condept of a 'link' which connects two nodes. Nodes do not store any neighbour information in them, instead they're stored in the links which are stored separately (a list of links, each link contain two integers representing the linked nodes' ids)

The train has no restriction on its movement it could move from A->B or B->A, only restriction is that it doesn't move to the previous node it came from. So going from A->B, when asking B of its neighbours, we exclude A and look at the other neighbours.

I hope that's enough context to answer my question: Is A* applicable to me? If so, I'm not really sure how to write a function to generate weights/costs on nodes. I just can't seem to answer the question of: What's the total distance between A->B in order to assign costs/distances? Because there could be more than one path to go from A->B, which requires path-finding in itself (see the infinite loop in my logic?). If A* is not the best here, what is?

[EDIT] Replying to Matt's answer. I thought of using distances to calculate the weights/costs but take this example for instance:

Where's at 'P' trying to go to 'T'. Edge/link 'A' is shorter than 'E' but if we take the 'A' route it would be longer in the long run. I would have to travel both the paths to determine which distance is shorter, otherwise how do I know? am I missing/misunderstanding something here?

Another question is, how do I track paths/links/nodes that I shouldn't visit anymore? I can't just mark a node as 'visited' once I visit it the first time because there could be a branch in there and I have to visit it twice to know which one is shorter, correct?

[EDIT] I guess in the first case^, it would be benefecial to also do the pathfinding backwards from 'T' to 'P' then pick which ever is the shortest between going P->T and T->A?


texts: Timers: check in game loop, or run independently?

texts:
Specifically talking in the context of JavaScript game development.
For example, I can use the language specific timeout mechanism:
// Timeout is not tied to game loop at all, tied to language specific timer loop
setTimeout(() => player.age += 1, 1000);

Or I can create some custom game timer
game.createFixedDelayTimer(() => player.age += 1, 1000);

// In update loop
let lastTimerCheckTime = Date.now();
function update(game) {
  checkTimers(game, lastTimerCheckTime); // Fire timer if specified delay has passed.
  lastTimerCheckTime = Date.now();
}

The disadvantage to approach 2 is that the checks are less granular... but maybe it's still desirable so that game behavior is deterministic?


texts: What does the Particle engine do and how are special effects created/processed?

texts:
For example, take bullets, sparks, fireballs, light sabers, lightning bolts, any kind of special effect in a game.

Are there various ways to implement these effects in a game. As far as I can see you create either an animation is some modelling package like Maya and then load these animations, you also seem to be able to do these kind of effects using layer upon layer of textures(images).

So where does the particle engine come in in a game, what is the relationship with pre-made animations.

Lets say I wanted to have some custom effect like the player could have a Thor like hammer and smash it on the ground as special power. Now when it hits the ground, everything rumbles and bolts of lightning appear from the hammer which propagate in a every increasing circular motion away from the hammer, like a circular lightning bolt and eventual fade away.

What options do I have to create a special effects like this, is it mainly done in animation software or mainly done in the engines code.


texts: How do I make sprites overlap eachother based on a layering system?

texts:
In Unity, I am building a 2D puzzle game, however I need to make sure that certain sprites are rendered on top of other sprites when they are above them.

Here is an example switch (left) and block (right).

I wanted to make sure that the green block appears on top of the green switch when it passes over it, so how do I avoid a situation like this happening?


texts: Box selecting (checking if rect contains selectable objects)

texts:
I'm trying to get a simple RTS-style box or drag select to work. Right now, the drawing of the rectangle works properly. I'm using OnGUI, and understand why one should generally avoid it, but I'll change it at some point. Currently, I'm interested in how to test to see if there are any selectable objects "contained" in the drawn rectangle using rect.Contains.

I have a simple script that transforms positions from world space to screen space.

public Vector2 screenCoordinates;

void Awake()
{
    screenCoordinates = Camera.main.WorldToScreenPoint(transform.position);
}

Then, here is the script which I want to attach to a Game Manager object.

public class BoxSelection : MonoBehaviour
{
    Vector2 boxStartPos;
    Vector2 boxEndPos;
    Rect selectionArea;
    public Texture texture;

    List<GameObject> selectableObjects;

    void Awake()
    {
        selectableObjects = new List<GameObject>();
    }

    void Update()
    {
        // if left mouse button is being clicked or held down
        if (Input.GetMouseButton(0))
        {
            // called on the first update in which the left mouse button is clicked
            if (Input.GetMouseButtonDown(0))
            {
                boxStartPos = Input.mousePosition;
            }
            // called on all other updates in which the left mouse button is held down
            else
            {
                boxEndPos = Input.mousePosition;
            }

            selectionArea = new Rect(boxStartPos.x, Screen.height - boxStartPos.y,
                                     boxEndPos.x - boxStartPos.x, -1 * ((Screen.height - boxStartPos.y) - (Screen.height - boxEndPos.y)));
        }
        // if left mouse button is neither being clicked nor held down
        else
        {
            // handle unit selection

            //if (selectionArea.Contains(*the screenpoint of selectable object*, true))
            //{
            //  add it to a list, activate that object's selection indicator... etc
            //}

            // Reset box positions
            boxStartPos = Vector2.zero;
            boxEndPos = Vector2.zero;
        }
    }

    void OnGUI()
    {
        // if box positions are not zero
        if (boxStartPos != Vector2.zero && boxEndPos != Vector2.zero)
        {
            Color textureColor = GUI.color;
            textureColor.a = 0.25f;
            GUI.color = textureColor;

            GUI.DrawTexture(selectionArea, texture);
        }
    }
}

The part under which I've commented "handle unit selection" is what I'm struggling with. I've written it in pseudocode I guess, but I'm not sure what the actual code should look like. Each object knows it's screen position since the simple screen point script is attached to them. But, the BoxSelection script doesn't have the references for which objects to test. Should I be doing this on a script attached to the selectable objects?

Thanks


texts: How to make a model parts glow one after the another

texts:
I have a brain model. I want to glow the parts of the brain model one after the another after a period of time. I have done to glow the parts, but when the second part glows, the color of the first part still remains.

public GameObject pons;
public GameObject frontallobe1;

void Update () {
    Invoke("PonsGlow",2);
    Invoke("frontalLobe1Glow",4);
}
void PonsGlow()
{
    pons.renderer.material.color=Color.red;
}
void frontalLobe1Glow()
{
    frontallobe1.renderer.material.color=Color.red;
}


texts: Joystick like controls in unity for mobiles

texts:
How can i achieve joystick like controls on mobile?

For example i have a 2D platform game where character should keep on moving right when swiped right and held and vice versa, just like a real joystick.

I'm beginner in unity so don't know where to start. Are there any assets in the store from which i can create these controls?


texts: Is there any way to change the layering of objects in Actionscript 3 without altering the run order?

texts:
I'm making a simple platformer in Adobe Animate, and I need the player to be layered in front of the stage because of a gimmick in the game. Unfortunately, whenever I change the layering order, it also seems to change the order that AS3 runs the instances.

Is there any way to change the layering order without affecting the instance order, or vice-versa?

I'm only just starting with programming, so please bear in mind that I probably won't understand many of the technical terms.

Thanks in advance!


texts:
I have a game where I want a never ending pathway for the character to walk along. So in my 3d modeling tool I created a path like this:

now I want to loop that model over and over in my prerendered 2d game for the character to walk on (most of the other game elements are in 2d). The problem is that simply overlaying one image on top of another results in the tiles facing opposite directions. Here's another picture I slapped together so you'll get the idea. In the final game the outer border of the pathway won't separate the two paths.

as you can see, the tile pattern looks unnatural, like one pathway segment is a mirror of the other. How can I change the lens/render the model differently so that it can become a seamlessly looping 2d texture?? Can it be done using only the camera view, without a "quadrilateral reshape" or falsely stretching the back end of the platform in my 3d modeler?


texts: How can I apply an overlay effect to a sprite in XNA?

texts:
Suppose I have a character sprite and I want to apply some animating effect that overlays its color, how would I do it? What I desire is something along this line:
(From final fantasy tactics)

It is a sprite overlay with animating gray effect and white color for black line.

However, in XNA, pixel shader support only shading of all sprite in the scene. If I am to pixel shade only specific sprite I want, I have to either apply stencil buffer which makes the system more complicated when I have multiple, separated effects for each sprite ( I have to determine stencil buffer clipping for each effects ). Another forum suggest using seperate sprite batch for each sprite drawn (call Begin / End for each sprite) and create my own sorting routine, but I found out that this batching method will really consume alot of GPU performance.

On the other hand, If I have 2D texture filled prerendered overlay effect, then I apply it onto the character sprite for some blending effect, the Sprite batch will not clip out the overlay effect and limit it only to character shapde but will pass it onto the background too.

Therefore, any suggestion to tackle this problem?


texts:
I'm using Phaser to create a small web based game, but I would like some advice on how to handle multiple resolutions and scrolling.
Basically what I would like to achieve is the following :

The game view must fit in a container (maybe smaller than the browser window) of any size and still cover it all
The aspect ratio must be maintained
The camera must follow the player and stop scrolling when the world’s bounds are reached

The world has a fixed size that never changes (pretty small).
The framework seems to already have everything required to do what I described.
For the game config I use:
{
    width: 1280,
    height: 700,
    scale: {
        mode: Phaser.Scale.ENVELOP
    },
    ...
}

Then for the camera:
this.cameras.main.startFollow(this.player);
this.cameras.main.setBounds(0, 0, this.gridSizeX * this.gridCellSize, this.gridSizeY * this.gridCellSize);

Very basic stuff, but the scale mode make the game area overflow its container.
That’s exactly what I want but the camera bounds become incorrect as demonstrated here:

Do you know a way to setup the camera to scroll until the end of the overflowing area ?
Thanks a lot!
EDIT:
I tried to change the size of the camera to make it equal to the size of the canvas' parent container, like this:
this.cameras.main.setSize(
    this.game.canvas.parentElement.offsetWidth,
    this.game.canvas.parentElement.offsetHeight
);

The result is:

In this example the size of the window is 1280x700 and the size of the container is 1024x560.
So setting the size of the camera to 1024x560 give the result above.
I'm getting confused.
Any idea?


texts: I am using Java to write a moderately simple video game and I need to transfer some large files (edit: Live game data and possibly assets.) between the client and the server. I need to decide whether I want to encrypt the data even though no sensitive information is being transferred. If I were to encrypt the data what method would be the best? Also, does encrypting data make cheating harder?


texts:
I'm currently using SFML 2.0 to develop a game in C++.  I have a game sprite class that has a click and drag method.  The method works, but there is a slight problem.  If the mouse moves too fast, the object the user selected can't keep up and is left behind in the spot where the mouse left its bounds.  I will share the class definition and the given function implementation.

Definition:

class codePeg
{
protected:
    FloatRect bounds;
    CircleShape circle;
    int xPos, yPos, xDiff, yDiff, once;
    int xBase, yBase;
    Vector2i mousePos;
    Vector2f circlePos;
public:
    void init(RenderWindow& Window);
    void draw(RenderWindow& Window);
    void drag(RenderWindow& Window);
    void setPegPosition(int x, int y);
    void setPegColor(Color pegColor);
    void mouseOver(RenderWindow& Window);
    friend int isPegSelected(void);
};

Implementation of the "drag" function:

void codePeg::drag(RenderWindow& Window)
{
mousePos = Mouse::getPosition(Window);
circlePos = circle.getPosition();

if(Mouse::isButtonPressed(Mouse::Left))
{
    if(mousePos.x > xPos && mousePos.y > yPos
        && mousePos.x - bounds.width < xPos && mousePos.y - bounds.height < yPos)
    {
        if(once)
        {
            xDiff = mousePos.x - circlePos.x;
            yDiff = mousePos.y - circlePos.y;
            once = 0;
        }
        xPos = mousePos.x - xDiff;
        yPos = mousePos.y - yDiff;
        circle.setPosition(xPos, yPos);
    }
}
else
{
    once = 1;
    xPos = xBase;
    yPos = yBase;
    xDiff = 0;
    yDiff = 0;
    circle.setPosition(xBase, yBase);
}
Window.draw(circle);
}

Like I said, the function works, but to me, the code is very ugly and I think it could be improved and could be more efficient.  The only thing I can think of as to why the object cannot keep up with the mouse is that there are too many function calls and/or checks.  The user does not really have to move the mouse "fast" for it to happen, I would say at an average pace the object is left behind.  How can I improve the code so that the object remains with the mouse when it is selected?

Any help improving this code or giving advice is greatly appreciated.


texts: How should I construct a Facebook Login Flow for a server-less Windows App in Unity?

texts:
I am game programmer with limited web experience that was tasked to figure out how to make our game interact with Facebook.  We are building a Unity Windows standalone app (maybe MacIntosh later), and our publisher wants us to enable the player to post in-game selfies to their wall in Facebook.  That is all we need to do, we do not need to touch their friends list or anything else like that at all.

I have been digging to find out exactly how to do this, and the available advice online or prebuilt Facebook API Asset Store packages rely on the mobile API which we can't use.  So, looks like we have to roll our own for the time being.  I have been reading the developers.facebook.com section on Login Flow and it says that we should

Request a login dialog for the player with our App ID
Take the Access Token out of the response
Then combine it with our App Secret to make API calls

Facebook also says that for security reasons, we should never embed the App Secret into the source of our client exe, so that hackers can't disassemble the exe and pull our secret out for them to use for their own purposes.  That makes sense.  Instead, they recommend that the App Secret remain on a server and that our client delegate API calls to that server.  Seems like a smart way to do it.

However, we don't have a server, our publisher won't pay us to make a server or maintain the hardware, and even if they did, we don't have time to make one. So, what is the best practice for a client-only native Unity standalone app?


texts: Why don't Sin and Cos give expected results when rotating off axis around a non uniform shape?

texts:
When I rotate a rectangle and draw straight lines along it's edge using Sin and Cos the lines don't follow the edge as the angle approaches 45 degrees, why? The exact same code works just fine when I use it on a square. See Gif:

Left object has the same width and height, No distortion of angles. Right side has larger X axis and lots of distortion.

Why does this happen and how do I prevent it?

Unity code:

[RequireComponent(typeof(Image))]
class rotation : MonoBehaviour
{
    [SerializeField]
    private float left = 180f, up = 90f;

    private void OnDrawGizmosSelected()
    {
        RectTransform rect = GetComponent<RectTransform>();

        Vector3[] corners = new Vector3[4];
        rect.GetWorldCorners(corners);
        float rot = transform.eulerAngles.z;

        Gizmos.color = Color.red;
        Gizmos.DrawLine(corners[3], corners[3] + new Vector3(
                Mathf.Cos((left + rot) * Mathf.Deg2Rad) * rect.rect.width,
                Mathf.Sin((left + rot) * Mathf.Deg2Rad) * rect.rect.height));

        Gizmos.color = Color.blue;
        Gizmos.DrawLine(corners[3], corners[3] + new Vector3(
            Mathf.Cos((up + rot) * Mathf.Deg2Rad) * rect.rect.width,
            Mathf.Sin((up + rot) * Mathf.Deg2Rad) * rect.rect.height));
    }
}


texts: How do I calculate the required force to launch an object?

texts:
I want to use a rigidbody AddForce() method on an object to launch it over from the enemy to the player, like throwing a ball at a target.
The problem is, I'm not sure how much force is required to use in the AddForce() method and it is taking too long to figure it out, and adding to that, the force would be different if I was farther away.
I found this helpful guide but it is not in 3D: https://forum.unity.com/threads/how-to-calculate-force-needed-to-jump-towards-target-point.372288/#post-2415612.
Could someone explain step by step in an easy to understand manner how to calculate the force required to get an object launched perfectly onto a target? (I'm not very good at math, haha...) Here's some images from that thread that will help illustrate the desired result:


texts: Constructor in derived class from MonoBehavior

texts:
So i've got a Part abstract class which inherit from Monobehavior

public abstract class Part:MonoBehaviour

And then I've a class frame which inherit from Part class

public class Frame: Part
{
    public Frame(string partId) {
    this.partId = partId;
    this.name = "Some Random name";
}

But on the last line which is this.name = "Some Random name";, i got this NullReferenceException.

Any suggestions would be appreciated.


texts: Can I reuse the name of an old arcade game?

texts:
I've done an indie remake of an old arcade game from 1980.

Can I use its name? I thought copyright expired after 25 years but I could be wrong, hence this question.


texts: How to use TextureArray's Pre-OpenGL 4.2?

texts:
I've been using TextureArray's in my current Project; However, I have come to the problem of OpenGL 4.2 functions not being on the present Mac software when ported over. Due to only version 4.1 of OpenGL being supported.

All my problems stem from the single function. glTexStorage3D which is the only function not supported.

This is how it currently works on my OpenGL 4.2 capable machine. (and works wonderfully I might add.)

1.) I allocate the memory beforehand with glTexStorage3D.

glGenTextures(1, &_texture);
glBindTexture(GL_TEXTURE_2D_ARRAY, _texture);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 255, GL_RGBA8, 16, 16, _maxLayerCount);

2.) Then per image I would load it into the before allocated memory block with the following.

glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, _layerCount, 16, 16, 1, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());

3.) Success.

How would I go about mimicking this functionality pre OpenGL 4.2 without using Immutable Storage? Aka (glTexStorage3D).

I've tried stuffing all my images into a horizontal single image and then loading that into just glTexImage3D with no success. Am I missing something?

Additional Note: I prefer to use TextureArray's for my project in order to avoid rendering artifacts I had using a TextureAtlas. It's simplicity during shaders is also a big plus.


texts: Pre baked fractures and explosion : I need an answer for C++

texts:
What are the prebaked or precomputed explosions or fractures from a programmer viewpoint ?

I would like to know how to achieve this in C++ and how this things are usually considered (they are animations? textures?), it would be perfect if there will be some examples available or someone that can picture a broad view about this.

I need to add a really small support for this in my code and i need an hint about how to start, i would like to do this on my own without other libraries.


texts:
I have and octree based world constructed (on the start) via marching cubes with certain density function to make a terrain (variations on noises). The terrain is rater smooth, it is not like minecraft blocky terrain at all. The deepest level of LoD is 12 and on this level (let's say) player is moving. The player have an ability to place blocks (just like in minecraft) and dig holes (block-like) in terrain. The blocks are stored as an overrides to density function so that the rendering algorithm looks if there's an override for each point of the certain marching cube block, and if there is, it constructs solid block, or hole there. Pretty simple.

The question is, what technique of LoD do you recommend, when I move away from the certain place where I have put my blocks to sustain details on lower LoD levels as much as possible?

I can see two ways there:

Render the terrain separately on each LoD and custom geometry (blocks) leave as they are. What this means is that my terrain will contain all blocks I placed rendered on LoD 12 while the terrain will be on appropriate LoD. This will lead to resource drain because all my custom blocks need to be rendered with maximum detail not depending how close I am to them, but on the other hand my house I built will look as house from the distance.
Just interpolate weights when switching to lower LoD level. This will be fast, but it will change how my blocks look (or should I say it will change a lot how looks whole my construction) drammatically - if I make a house from blocks and move away, my house won't look as house anymore.