texts: Unity problems with OnTriggerStay and Input.GetKeyDown

texts:
Background information

Some weeks ago, I start by creating my own platform game. You control a character, that can collect logs and should hold all the campfires on in the game.
When the user has collect more then one log, the player have to use this log to hold the fire on. So you should walk to the campfire and should press E to give the log to the fire.

Problem

What the problem momently is, is that when I press the E key, it will fired the input more then one time. This is because I use a OnTriggerStay2D function, to check every second if my Player is collide with the campfire object.

Do some search on the internet, results in people with the same problem. So one of the solutions was to create an bool and set it to true on OnTriggerEnter2D. But this isn't working for me. The same problem as before will occur.

Is there another solution to fix this conflict. When the user press the button, it should be fired ones. Below script is linked to the campfire object.

Also tried it with: if(Input.GetKeyDown(KeyCode.E)) { isTrigger = true; } and the same for GetKeyUp, but then isTrigger = false;

My current working code:

public Animator anim;
    public int campfireStatus;
    bool inTrigger = false;

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

    // Update is called once per frame
    void Update () {
        anim.SetInteger("Intensity", campfireStatus);
    }

    void OnTriggerEnter2D(Collider2D other) {
        inTrigger = true;
    }

    void OnTriggerExit2D(Collider2D other) {
        inTrigger = false;
    }

    void OnTriggerStay2D(Collider2D other) {
        // If player comes in contact with gameObject
        if (other.gameObject.tag=="Player"){
            print ("player");
            if(Input.GetKeyDown(KeyCode.E)) {
                print ("E Pressed");
                if (WoodBehaviour.count > 0) {
                    campfireStatus++;
                }
            }
        }
    }

So when the Player is collide with the campfire object AND the player pressed the E key AND you have more then one logs (this counter will be set in the WoodBehaviour script, that is linked to the player object ) than it should increase the campfireStatus with plus one.
The problem is, that the if statements will fired more then one times when pressing the E key.


texts:
I have probably dumb problem with a text-mesh game object. I want to use it as a title on a top of container. I will give you all information that you need to find a problem.
I'm using pixel font Tripfive.

In game result:

In scene result:

3D:

text gameObject settings:

all other settings that can be realted to the scene:


texts:
I'm currently trying to make a crafting system. For a little background I have a json file with crafting recipes. I check each of these recipes against the items I have in another list which holds the 4 items currently selected for crafting.

My current method is as follows:

private bool DoListsMatch(List<int> list1, List<int> list2)
{
    return list1.TrueForAll(list2.Contains) && list2.TrueForAll(list1.Contains);
}

At first this method looks like it's working. However, when I change the last item in the crafting window it still returns a result when it shouldn't. This suggests to me that the method is not working.

Is there any other ways of checking if lists match completely?


texts:
I have programmed an OpenGL game which just contains one F1 car and a track. It is very simple and only uses around of 10'000 - 20'000 triangles. It should run on any PC but it won't, it needs a really good graphics-card to run at a decent framerate. Can you write some methods or links to sites which would help me make my scene/game more efective?

my game can be downloaded from here

or directly from here


texts: Unity c#: How to slow down rotation over time?

texts:
I am making a space combat game, in which the player can press q and e to roll their ship. I did this by adding torque to the rigid body when the player press q or e. However, after they do so, they keep on rotating. How do i make the angular velocity slowly go back to zero?

I tried using angular drag, but that does not work.

public float TurnSpeed;

public Rigidbody rb;

float currentturn;

Vector3 turn;

float turnEnabler;

bool iszero;

public float dampener;

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

    rb.AddTorque(new Vector3(0, 0, turnEnabler));

    if (Input.GetKey("e"))
    {
        turnEnabler -= TurnSpeed;
    }

    if (Input.GetKey("q"))
    {
        turnEnabler += TurnSpeed;
    }

    rb.angularDrag = dampener;

}

}


texts: Calculating the poly vertices based on the result of Connected Component Labeling

texts:
I am making a tile based game.

And now I can find all the connected area using the Connected Component Labeling algorithm.

But now the problem I am having is how to calculate the poly vertices of each connected area.

For example:

As you can see all the YELLOW tiles are of the same AREA and with the help of Connected Component Labeling algorithm I know all the (x, y) info of each tile.

And now I want is the generate a poly vertices array for the YELLOW AREA POLY (clockwise).

Is there any good algorithm for this ?

Any suggestion will be appreciated, thanks :)


texts: How should I determine direction from a phone's orientation & accelerometer?

texts:
I have an Android application which moves a ball based on the orientation of the phone. I've been using the following code to extract the data - but how do I use it to determine what direction the ball should actually travel in?

public void onSensorChanged(int sensor, float[] values) {
    // TODO Auto-generated method stub
   synchronized (this) {
        Log.d("HIIIII :- ", "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
        if (sensor == SensorManager.SENSOR_ORIENTATION) {
            System.out.println("Orientation X: " + values[0]);
            System.out.println("Orientation Y: " + values[1]);
            System.out.println("Orientation Z: " + values[2]);
        }
        if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
            System.out.println("Accel X: " + values[0]);
            System.out.println("Accel Y: " + values[1]);
            System.out.println("Accel Z: " + values[2]);
        }
    }
}


texts:
I've found this post Turret Aiming Formula on Reddit and a nice answer a while back.

The solution in the answer works great for still sanding turrets but is almost unusable for moving turrets since the speed of the turret is not applied to the bullet speed. The bullet still have the same fixed speed all the time but should be faster if the turret is moving in the same direction.

There are also a lot of answers here, but non of them respects the speed of the turret.

Is it possible do integrate turret speed into this formula or is there any other known solution?

My current code without turret speed:

Vector2f toTarget =  target.position - attacker.position;

float a = Vector2f.dot(target.velocity, target.velocity) - (bulletSpeed * bulletSpeed);
float b = 2 * Vector2f.dot(target.velocity, toTarget);
float c = Vector2f.dot(toTarget, toTarget);

float p = -b / (2 * a);
float q = sqrt((b * b) - 4 * a * c) / (2 * a);

float t1 = p - q;
float t2 = p + q;
float t;

if (t1 > t2 && t2 > 0){
    t = t2;
}
else{
    t = t1;
}

Vector2f aimSpot = target.position + target.velocity * t;

update:

the solution is to use relative velocity instead of target.velocity as suggested in the answer

relativeVelocity = target.velocity - attacker.velocity

and then use bulletSpeed + attacker.velocity for the bullet velocity


texts:
The polygon slice function of TexturePacker Pro is very nice, it suit the size of the sprite. However my TexturePacker Pro trial had finished, and by using Unity Sprite Editor will make my sliced sprite tremble, I don't know why.

How can I use Unity Sprite Editor to slice my sprites correctly?


texts: How does one load TMX files into a SFML game?

texts: How does one load .tmx files from Tiled into a SFML game?


texts: How difficult is it to implement 3D models in a 2D game?

texts: Creating a full blown 3D game requires a lot more math for physics, but what if I just want to mix 3D models in a 2D game, such as in the New Super Mario Brothers? Would I be able to get the looks of 3D models with the ease of making a 2D game?


texts: Dealing with ghost vertices of Kinematic bodies in Box2D

texts:
I'm using LibGDX and Box2D and I want to have multiple falling platforms in a row which will fall sequentially as the player runs on them, like in the picture below. (the shapes are parsed from Tiled)

When I use simple rectangles I have the problem of ghost vertices.

Chain shapes eliminate them but according to the documentation they are meant for static bodies. I actually gave them a go and indeed when I set a velocity to the Kinematic body they just disappear.

Any idea how I could tackle this? Excuse me if it's something fairly simple, I'm new to box2d.


texts: Is it possible to do freelancing with 3dsmax?

texts:
I am learning 3dsmax architecture for building models of houses. Is it possible to do freelancing with house modelling thing?  For various reasons I have to stay at home.

So I was wondering if I can earn some money by making some house models for someone.

I really don't know how this works but may be someone can give some ideas.

Would I need to go to construction or real estate companies and ask them if they want something like this?


texts:
We have a set of buttons in our game. Each one corresponds to a particular instrument. we have to implement the foll:

a button should become deactivated after being clicked once implying that the same instrument should not be taken twice.

how to accomplish this?


texts: Is it acceptable to say "Inspired from ... game"

texts:
For a game I'm developing, I would like to use "inspired from ... game" to acknowledge and praise that game. But I'm not sure if this is a good idea from a legal point of view. They might think my game is a ripoff, and base the claim on my word.

Any ideas?


texts: 108 kb - size of most in-game activation passes, skins, etc... Any idea Why?

texts:
I have been playing xbox 360 for a while now and whenever there is a pass, character/weapon skin or even multiplayer access code that needs downloading, the file size is usually 108 kb, no matter the game/application. I've tried googling around and have not come across anything useful. Could someone explain or even speculate why that happens?
I ask out of curiosity :)
Possibly, this question may belong in a different forum - if so, please advise which. :)


texts: OpenGL additive blending not working as expected

texts:
I am trying to achieve additive blending with point sprites.  When the sprites overlap, all I get is solid red, when I expect to get a smooth blend from red->yellow->white.  My sprite texture has all four channels set equal, with portions being white and others transparent.

I set up blending as such:

  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE);

My fragment shader is as follows:

  vec4 texCol = texture(pointsprite, gl_PointCoord);
  colorOut = vec4(texCol.rgb * vec4(ocolor, 1.0).rgb, texCol.a);

Where pointsprite is a sampler2D and ocolor is `(1.0, 0.0, 0.0)

My background is cleared as

  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

I have tried some of the various methods suggested in this question, none offering any results.  I can verify my alpha channel is correctly loaded from my image into my texture.

EDIT: Missed mentioning that my intention is for clusters of point sprites with the same pigment (red) to additive blend to yellow and white.


texts: Rotating 2D bone in LateUpdate have jittering issue

texts:
I made a skinned 2D character and applied IK to each hand and leg.

In my game, player can aim up and down by moving fire joystick up and down. This is implemented by update "chest" bone's rotation in LateUpdate, because it renders after all animation stuffs.

Here'e the code I'm trying:

void Update() {
    // Handle move forward & backward
    ...

    m_FireMovement = new Vector2(m_FireJoystick.Vertical, m_FireJoystick.Horizontal);
    m_DeltaTime = Time.deltaTime;
}

void LateUpdate() {
    float verticalMovement = m_FireMovement.x;
    float horizontalMovement = m_FireMovement.y;

    // Which side facing? Depends on Fire Joystick.
    if (horizontalMovement < 0) {
        transform.rotation = Quaternion.Euler(0, 180, 0);
    }
    else {
        transform.rotation = Quaternion.Euler(0, 0, 0);
    }

    // Rotate chest bone depends on vertical input
    // TODO: Fix jittering issue
    float newRotation = verticalMovement * m_AimAmount * m_DeltaTime;
    m_ChestBone.Rotate(0, 0, newRotation);
}

It works, but there is noticeable jittering issue when aim up and down. Here's the video I recorded for demonstration: https://youtu.be/eYCY0NRG_AA

So I tried with using Coroutine, invoked from "Start" and keep looping and wait until WaitForEndOfFrame, and try rotate chest bone, but that makes it worse.

In 3D project, rotating bone in LateUpdate didn't make any problem. What am I missing?

Using Unity 2019.1.0f2 and 2D Animation Package@2.1.0, 2D IK@1.1.0.


texts: Overview/showcase of shader techniques/uses for games

texts:
I am looking for resources that can provide me with a better understanding of what kind of things shaders are used for in games, what they can do, and maybe even more importantly, what they cannot. I understand how the graphics pipeline works and all that, and I have made some very basic shaders in GLSL (mostly just to replace the fixed-function pipeline functionality), but I don't yet fully understand which things are only possible with custom shaders, which things can be done more efficiently, etc. I have been able to find some examples of certain techniques, most notably lighting, but I am looking for a more higher-level overview of their usage.

Links to and explanations of certain interesting techniques, as opposed to an overview, are also appreciated (but less than an overview ;) ), preferrably in GLSL or pseudocode.


texts:
In the first tutorial for GameMaker (catch the clown), I want to set the direction of the clown after the collision with the wall.

I want to do it by pressing the wall object with the mouse (before the collision, to set the angle parameter). For example by pressing only once the wall object it would change the clown's direction after collision by 45 degrees, twice by 90 degrees, and so on.

How can I do that?


texts: What formula is commonly used in rpg based games to calculate gained currency?

texts:
Assuming I have an RPG game with monsters, a game you can fight any amount of monsters at any time - What are my options for a gained currency from a battle formula? I've been trying to use Google for any ideas, but couldn't find something solid.

Currently I have the enemy level * user level * 0.1

Pretty sure I need something more realistic and randomized, Hope someone can share any idea about it.

Thanks in advance!


texts: Programmatically change combination of sprites

texts:
I am a total newby to unity and cannot figure out how to achieve the following:

I want to show a picture composed of different sprites. E.g., a pen with four binary features: the pencolor (black or silver), the penshape (ballpen or normalpen), an ornament (blue or orange), and the tintcolor (blue or black).

My goal:

A function taking a numerical vector as input to specify which of the features/attributes of the pen to show.

0,0,0,0 = a black ballpen with blue ornaments and blue
tint.
1,1,1,1 = a  a silver normal pen with orange
ornaments and black tint.
... and all combinations in between.

One constraint: I need to be able to change how many features there are, and how many values they take.

The sprites are stored in a sprite with mode "multiple" and I use unity to create the layers.

What I did so far:

1) Define an object holding the feature sprites

To enable changing how many features and feature values there are I created a structure. It has flexible length specifying the number of features. Each feature is sprite array specifying the number and source of the featuer values.

// New object class holding all visual feature sprites in hierarchical vectors
[Serializable]
public struct Feature
{
    public string Name;
    public Sprite[] FeatureValues;
}

public Feature[] Features;

This allows me to specify how many features, how many different sprites per feature, and to drag and drop the respective sprites onto the associated elements of the Features structure.

2) Defined a Prefab for the Pen

With the help of this post on displaying multiple sprites I created a prefab with as many layers as there are features of the pen

3. And now ... ?

Based on the first comment I created Sprite Renderers for all sub-elements of the Pen object.

The Pen object is a prefab.

Can anyone help me how to change the values of the sprite?

I am trying this: Based on the link mentioned above I create a new class for Pen objects with some sprite renderers

public class Pen : MonoBehaviour {

public SpriteRenderer Tintcolor;
public SpriteRenderer Casecolor;
public SpriteRenderer Ringcolor;
public SpriteRenderer Shape;

public void setTintcolor (Sprite featureImage)
{
    Tintcolor.sprite = featureImage;
}
public void setCasecolor (Sprite featureImage)
{
    Casecolor.sprite = featureImage;
}
public void setRingcolor (Sprite featureImage)
{
    Ringcolor.sprite = featureImage;
}
public void setShape (Sprite featureImage)
{
    Shape.sprite = featureImage;
}

}

Then I write a function to change the value of the sprite renderer.

// featureCombination is the vector holding the feature values to be displayed
public void ShowFeatureCombination(int[] featureCombination)
{
    Pen newPen = Instantiate(penPrefab) as Pen; // new Pen object

    newPen.setTintcolor(Features[0].FeatureValues[featureCombination[0]]);
    newPen.setCasecolor(Features[1].FeatureValues[featureCombination[1]]);
    newPen.setRingcolor(Features[2].FeatureValues[featureCombination[2]]);
    newPen.setShape    (Features[3].FeatureValues[featureCombination[3]]);
}

This does not work so far.

And it requires to manually specify the spriteRenderers, which i need to have automatically done based on the number of different features that I enter in the Feature structure.


texts: Initializing Consumable product to an amount on first use

texts:
I am using Unity's In App Purchase plugin to implement an in game store. In my game every player has fuel. I'd like to use the plugin in order to keep track of the amount of fuel the player has so that just erasing the cache on the phone or something wouldn't effect the regeneration time of fuel (like it would if I use PlayerPrefs).

Right now i have it setup so the fuel amount is saved in PlayerPrefs and when fuel is used, a timestamp is saved in PlayerPrefs. Then it checks every once in a while if enough time has passed since they used it in order to regenerate it.

Instead of doingoing it this way I want to initialize the fuel amount in Unity's in app purchase plugin so that Googles servers will have the amount and then I can use the same idea for regeneration that I already have but nowe the amount will be more safe.

Is there a way to initialize the amount of a consumable product a player has on their first launch of a game?


texts:
I'm going to make a snake remake with SDL library and right now I'm thinking heavily about the object-oriented design.

I can imagine that I will have classes like GameEngine, Snake, Board and Food, but the interesting part is - how shall they interact between each other? How shall the game logic be designed?

For example, let's imagine here are some of the possibilities:

Every class except of GameEngine will hold only it's data (position of snake, food, etc.). All the game logic will be done in engine's Update() function. Therefore this function will be very big and every other part of the program fairly small.
GameEngine will only call appropriate functions of every object with the reference to Board and these individual functions will take care about the game logic.
something other

So I would like to know your opinion - what approach do you think is the best? I'm not aiming at low number of lines the game will have, but at the quality and "modularity" of the game object design.


texts: Strange javascript error when using Kongregates API

texts:
In the hopes of finding a fellow unity3d developer also aiming for the Kongregate contest..
I've implemented the Kongregate API and can see that the game receives a call with my username and presents it ingame. I'm using Application.ExternalCall("kongregate.stats.submit",type,amount);
where type is a string "Best Score" and amount is an int (1000 or something).
This is the error I'm getting:

You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.
callASFunction:function(a,b){if(FABrid...tion, can be used as a workaround.");

I'm wondering, has anyone else had this error or am I somehow doing something stupid?
Thanks!


texts: Name doesn't exist in current context in Unity

texts:
I'm currently making a collectible heart in unity, the kind that updates your health bar when you collide with it, and I made two scripts:

This one is called 'healthmonitor':

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

public class healthmonitor : MonoBehaviour {

public static int HealthValue;
public int InternalHealth;
public GameObject Heart1;
public GameObject Heart2;
public GameObject Heart3;

void Start () {
    HealthValue = 1;
}

void Update () {
    InternalHealth = HealthValue;

    if (HealthValue == 1) {
        Heart1.SetActive (true);
    }
    if (HealthValue == 2) {
        Heart2.SetActive (true);
    }
    if (HealthValue == 3) {
        Heart3.SetActive (true);
    }

}
}

This one is called 'hearstscript':

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

 public class heartscript : MonoBehaviour {

public int Rotatespeed;
public AudioSource CollectSound;
public GameObject thisheart;

void Update () {
    Rotatespeed =10;
    transform.Rotate(0, Rotatespeed, 0, Space.World);
}

void OnTriggerEnter () {
    CollectSound.Play ();
    HealthMonitor.HealthValue += 1;
    thisheart.SetActive (false);
}
}

Here is a picture of my UI:

I made an empty game object and named it HealthMonitor and applied the healthmonitor script to it. Here's a picture of the inspector panel:

The problem is that with heartscript I get the following error;

  Name "HealthMonitor" doesn't exist in current context.

I believe it relates to this line:

HealthMonitor.HealthValue += 1;

P.S. I am trying to refer to the empty game object, not the script.


texts:
i'm working on a 2D RTS project, no tile-based map. I have a problem on building map data structure & algorithm for that. I already think of a naive algorithm to solve that. Of course it's very slow. I'm looking for an advice from who experienced  :D

At very first, i have a list of obstacle as polygon like that

i decided to build a pathfinding graph, then i travel all pairs of node, connect them if the connection segment doesn't intersect any polygon. this process have O(n^2) time complexity.

after that, on every path query, i try connect every node to A(startnode) and B(goal node), then do dijstra to find path. this process have O(2n) + O(nlogn) time complexity.

That's all, my algorithm works fine(even it's slow) if the environment is static, no insert, remove obstacle. But when the environment turn to dynamic, such as a obstacle removed, i need to rebuild pathfinding graph(O(n^2)), my fps extremely decreased, 120 to 10.

Is there a more professional aproach to solve my problem?


texts: It looks like 2048 is a registered trademark of Ketchapp (obviously not the original author of 2048): https://trademarks.justia.com/865/87/2048-86587551.html . How applicable is this trademark and why are there still dozens of clones of 2048 on both Apple/Google Play store?


texts: How did EA DICE create destructible environments in Battlefield Bad Company 2 and Battlefield 3?

texts:
How did the folks at EA DICE create destructible environments in Battlefield Bad Company 2 and Battlefield 3?

Did they just assemble the buildings out of predefined sub-regions, that break apart when there is an explosion or something similar? I can't think of anything else.


texts: Desire advice on implementing this animation timeline system

texts:
I have read a lot of questions on here, as well as books regarding game architecture. I have a general question about the implementation of a game's animation timeline, on which many isolated animations sit. I implemented one recently that proved rather inefficient and bug-prone, so I'm doing it again but this time seeking some advice. According to one book I've looked at, the implementation of a timeline does not have a well-known standardized technique and everyone seems to roll their own. Perhaps some of you can offer advice.

Here is the general situation, where "Time" is the game's passing time, starting at 0 when game launches:

The task: Finding the best data structures to be used such that I can throw any arbitrary value of t at the timeline entity and retrieve the active animation objects at that point in time, and finding these quickly. (Note: this is not a question about finding keyframes, but rather about finding valid animation objects on a timeline of many scheduled animations.)

I am using STL for simplicity. One idea I thought of was to have a general map of animations as my timeline, where the map's key was the start time, since maps automatically sort based on keys. Then, for any value of t I can stop iterating as soon as the key is a value higher than t since I know the animation has not started yet.

But this seems inefficient:

I would always iterate from the beginning, even for animations that have already completed. I don't want a technique that stores flags or pointers for completed animations, because I want to always be able to jump to any t and get active animations for that point in time.

Another problem, the map can only have one key, in this case the start time. To know if an animation is active, the algorithm must also peer inside the value of the map to see if its duration has been completed yet. This seems wasteful, surely there is a better way.

I think you get the path I'm going down, and I know this is an issue that everyone tackles. Any advice?


texts: Why does my custom network Manager disable the main one

texts:
Whenever I add a custom Network Manager to add functionality to and override it's functions, the main NetworkManager got disabled so I could not see the NetworkManager HUD or start matches. It there a way around that?

(EDIT)
[Thanks for the response]
It's not just the HUD that's the issue. The Networking is disabled entirely. Can I change this through a custom HUD?


texts: blending with OpenGL glBlendFunc and glBlendEquation

texts:
I want to draw a bunch of images in front of a background. Where images overlap, I want those to be blended together (for now, using a mix of 0.5 source * 0.5 destination color every time an image fragment gets drawn on top of another image's fragment). Any background that existed before I drew the images should just be overwritten.

So basically I want:

when an image is drawn on top of the background: output color := image color
when image A is draw on top of image B: output color := 0.5 * (color A + color B)

What I've tried is the following:

    // clear the alpha channel of the background already in the framebuffer:
    GLES20.glColorMask(false, false, false, true);
    GLES20.glClearColor(0, 0, 0, 0); // clear with alpha == 0
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
    GLES20.glColorMask(true, true, true, true);

    // enable blending for drawing the images
    GLES20.glEnable(GLES20.GL_BLEND);
    GLES20.glBlendEquation(GLES20.GL_FUNC_ADD);
    GLES20.glBlendColor(0, 0, 0, 0.5f);

    // The alpha blendFunc is chosen such that the resulting alpha
    // will be 0.5 in any pixel that had already an image fragment
    // drawn. In those pixels still holding the background, the
    // alpha should be 0 based on the glClear() above.
    // For those pixels holding the background,
    // GL_ONE_MINUS_DST_ALPHA * srcColor + GL_DST_ALPHA * dstColor
    // should equal srcColor because dstAlpha is 0.
    // For those pixels already holding an image fragment,
    // GL_ONE_MINUS_DST_ALPHA * srcColor + GL_DST_ALPHA * dstColor
    // should be 0.5 * srcColor + 0.5 * dstColor because dstAlpha
    // will be 0.5
    GLES20.glBlendFuncSeparate(GLES20.GL_ONE_MINUS_DST_ALPHA, GLES20.GL_DST_ALPHA,
            GLES20.GL_CONSTANT_ALPHA, GLES20.GL_ZERO);

    imageShaderProgram.draw(viewProjectionMatrix);

    GLES20.glDisable(GLES20.GL_BLEND);
    [...draw some further foreground...]

However, I can't get this to work. The result is that the background that I've drawn ahead of the blending still appears unaltered, and the foreground that I draw afterwards also appears. There is no trace at all of the content (imageShaderProgram.draw(viewProjectionMatrix)) that I drew while blending was enabled.

If I drop the glEnable(GLES20.GL_BLEND), my images get drawn (but of course not blended).

This all looks just as if the dstAlpha was always 1 rather than 0 or 0.5 like I'm trying to make it. So I suspected my glClear(GL_COLOR_BUFFER_BIT) not working right. But when I change the glColorMask to (true, false, false, true), the background's red color component is cleared, so I don't see why (false, false, false, true) wouldn't set the framebuffer's alpha channel to 0 like I intended.

Any idea what I might be doing wrong?


texts:
Is it possible to use animated .gif  images in lbgdx? If not how whats the alternative? We need to include animated buttons.

When I use an animated gif, the animation won't play. This question (and many others) states that Libgdx doesn't support it, I'm wondering if something has changed over the years


texts: In a shader how to map UV coordinates of texture to the UV coordinates of a tile in a tile set?

texts:
I am writing a fragment shader for a tile set. In the shader I have the UV coordinates of the whole texture, however, I am interested in the UV coordinates of the current tile that is being rendered. In other words: in my shader I am interested to know where the current pixel is within the current tile, not within the whole texture.
So given the overall texture size and the rectangle that defines the tile to render within that texture, and given the UV coordinates of the current pixel corresponding to the whole texture, how can I convert these UV coordinates to the "inner" UV coordinates of the current tile, but also in the range of [0.0,1.0]?


texts: Should I finish high school or teach myself?

texts: I want to become a game developer, I am an A student in 11th grade and feel like I am wasting my time in High School. I'm thinking of switching to homeschooling so that I have more time to focus on learning game development on my own while finishing high school at home. Some people I spoke to about this say its better to stay in school and go to college, some say I can get my diploma through homeschooling and this way I can get a head start on what I love to do, and get hands on experience. I am not sure what to do and was wondering if there are any experienced programmers out there that can give me advice on what route I should take??


texts: How do I calculate opposite of a vector, add some slack

texts:
How can i calulate a valid range (RED) for my object's (BLACK) traveling direction (GREEN). The green is a Vector2 where x and y range is -1 to 1.

What I'm trying to do here is to create rocket fuel burn effekt. So what i got is

rocket speed (float)
rocket direction (Vector2 x = [-1, 1], y = [-1, 1])

I may think that rocket speed does not matter as fuel burn effect (particle) is created on position with its own speed.


texts: Havok physics with a wide range of object scales

texts:
So typically Havok works best with normal human sized objects with a gravity of 9.8m/s^2 and dealing with everything in meters.

In my Game though there will be a large variety of scales from millimeter sized objects to meter sized objects.

Typically this rules out running a standard Havok setup and dealing with things in a meter scale.

Would it be best to increase everything by 10x or some scalar like this and increase gravity likewise?

I understand this would also decrease how far objects can be away from the origin but for the sake of this question assume everything is relatively close to the origin, a hundred meters max.

Issues of concern

Object penetration - Havok usually allows some object penetration in the 2-3cm range in the meter scale.

Floating point precision - Issues dealing with distances of objects etc, typically physics breaks down at the kilometer scale in Havok.

Unseen - other unseen issues that may result with such large differences in scale.


texts: Storing quests for an online RPG in a MySQL database

texts:
I'm creating an online RPG game and I've been looking around for a way to save players' progressions in quests in MySQL. I've been looking at Pim Jager's answer answer for a while and I've come to the conclusion that this could work, but then my question would be:

Where/how do I store if a player currently has a quest accepted? How do I keep track of at which step of the quest the player currently is? This has to be saved somehow but I can't seem to figure out how I would do that. Let me know if you can help me out.

Thanks!


texts: 45° Slopes in a Tile based 2D platformer

texts:
I want to have simple 45° slopes in my tile based platformer, however I just cant seem to get the algorithm down. Please take a look at the code and video, maybe I'm missing the obvious?

//collisionRectangle is the collision rectangle of the player with
//origin at the top left and width and height
//wantedPosition is the new position the player will be set to.
//this is determined elsewhere by checking the bottom center point of the players rect
if(_leftSlope || _rightSlope)
{
    //Test bottom center point
    var calculationPoint = new Vector2(collisionRectangle.Center.X, collisionRectangle.Bottom);
    //Get the collision rectangle of the tile, origin is top-left
    Rectangle cellRect =
        _tileMap.CellWorldRectangle(
            _tileMap.GetCellByPixel(calculationPoint));
    //Calculate the new Y coordinate depending on if its a left or right slope
    //CellSize = 8
    float newY = _leftSlope
                            ? (calculationPoint.X % CellSize) + cellRect.Y
                            : (-1 * (calculationPoint.X % CellSize) - CellSize) + cellRect.Y;
    //reset variables so we dont jump in here next frame
    _leftSlope = false;
    _rightSlope = false;
    //now change the players Y according to the difference of our calculation
    wantedPosition.Y += newY - calculationPoint.Y;
}

Video of what it looks like:
http://youtu.be/EKOWgD2muoc


texts: Do I have to credit the author of a free asset from the asset store?

texts:
Am sure that some people have been asked this question, and my researches yields a no, but I want to know from here. Do I have to credit the owner of a free asset that I used for my project from the unity asset store?
Example: if I download a model from the unity asset store and use it in a game design, do I have to give credits to the person that provided the model on the asset store?
Like this: https://assetstore.unity.com/packages/3d/characters/humanoids/scifi-robots-113422


texts: Is it bad practice to store inventory and scores in PlayerPrefs?

texts:
I'm building a mobile game for a client in Unity. To save time, we started with a template game from the Asset Store that had some of the features that the client wants.

The game includes a progression system and shop, so we save the user's scores,  progress, in-game currency, inventory, etc. We currently have no plans to export the save data.

The template game uses PlayerPrefs to store all save data. Is this bad practice? Assuming we don't include a button that calls PlayerPrefs.DeleteAll(), is there any extra risk associated with using PlayerPrefs instead of external files to store the player's data?


texts: Sprite doesn't change material or picture

texts:
I am quite new to unity and currenty I'm practicing with a 2D topdown game.

I created a tile map with "tiled", imported it in Unity with "TiledToUnity" and changed some things like player movement, camera and so on.

Now I wanted to create collectible coins. So I created a new 2D Sprite and added the picture of the coin I had to it. But the picture of the coin did not change. I tried the same with adding a material with the coin as picture but it did not work out either.

To check if the object is even there I added a collide box to the coin and my player body did indeed collide.

What did I do wrong while adding a picture to the sprite?

Thanks in advance!

(Sorry fotgot the pictures. )
-- Edit--


texts:
From waht I understand, Collider.Bounds are the sides or bounds of the collider of the GameObject (at least for a cube with a BoxCollider). But I got a result that I wasn't expecting when I tried moving a cube continuously downwards and drawing the bounds with lines. While moving frame by frame, the collider bounds seemed to be not bounding the cube (or at least that's what my test is showing, if my test is correct).

Here's 3 frames of screenshot:

What I did for this is create a new 3D project, add a Cube, then added a single script and then added this script to the Cube. The whole script is:

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    Vector3 velocity;

    // Start is called before the first frame update
    void Start()
    {
        velocity = Vector3.zero;
    }

    // Update is called once per frame
    void Update()
    {
        velocity.y += -0.5f;
        transform.Translate(velocity);

        Bounds bounds = GetComponent<Collider>().bounds;
        Debug.DrawLine(new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), Color.red);
        Debug.DrawLine(new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), Color.red);
        Debug.DrawLine(new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), Color.red);
        Debug.DrawLine(new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), Color.red);
        Debug.DrawLine(bounds.min, bounds.max, Color.red);
    }
}

Am I not understanding something or am I doing something wrong?


texts: Building a unified interface for a swap chain in both DirectX 12 and Vulkan

texts:
Most objects in DirectX 12 have natural analogues in Vulkan, e.g.

VkInstance = IDXGIFactory
VkPhysicalDevice = IDXGIAdapter
VkDevice = ID3D12Device
VkQueue = ID3D12CommandQueue
VkCommandBuffer = ID3D12CommandList

However, when it comes to the swap chain, it's not clear how the entries in VkSwapchainCreateInfoKHR correspond to entries in DXGI_SWAP_CHAIN_DESC1.
Clearly, there is not always a 1-1 correspondence, but I would really like to know how I can implement a unified interface for both.


texts: Triangulating a partially triangulated mesh (2D)

texts:
Referring to the above exhibits, this is the scenario I am working with:

starting with a planar graph (in my case, a 2D mesh) with a given triangulation, based on a certain criterion, the graph nodes are labeled as RED and BLACK. (A)
a subgraph containing all the RED nodes (with edges between only the directly connected neighbours) is formed (note: although this figure shows a tree forming, it may well happen that the subgraph contain loops) (B)

Problem: I need to quickly build a triangulation around the subgraph (e.g. as shown in figure C), but under the constraint that I have to keep the already present edges in the final result.

Question: Is there a fast way of achieving this given a partially triangulated mesh? Ideally, the complexity should be in the O(n) class.

Some side-remarks:

it would be nice for the triangulation algorithm to take into account a certain vertex priority when adding edges (e.g. it should always try to build a "1-ring" structure around the most important nodes first - I can implement iteratively such a routine, but it's O(n^2) ).
it would also be nice to reflect somehow the "hop distance" when adding edges: add edges first between the nodes that were "closer" to each other given the start topology.

Nevertheless, disregarding the remarks, is there an already known scenario similar to this one where a triangulation is built upon a partially given set of triangles/edges?


texts: Can I use a BlendState object to emulate a draw call's blending color?

texts:
I'm working on a lighting system for a tile-based game.

What I want to do is draw my tiles to the screen, then draw a single Texture2D object (my light map) over top of them. However, doing it in two steps results in the tiles looking "painted" and washed out.

To get this effect working, I called Texture2D.GetData() and then used that Color as the blending color when calling SpriteBatch.Draw() on each tile, which results in them being "tinted" correctly. This works, but it's a fair bit slower, and won't scale up for huge maps/view areas.

So, is it possible to use a BlendState object to do what I am doing above?

Tile map
Light map
Tile map with light map applied (per tile)


texts: What kind of data structure should I use for a resource container?

texts:
I am curious what kind of container would be the best choice for a resource container.
BTree, binary search tree or something else?
What like is the priority of the operations over it?
So best inserting performance or best searching performance or between them?

Are there any open source implementation over the net?


texts:
I am just diving into the Stage3D APIs for Flash Player 11.  I am trying to figure out a simple way to display isometric 2D content that gets blitted from a sprite sheet onto a 3D cube.  The idea being that then the isometric content can be split into the appropriate quads of the cube and handed over to the GPU.

I found this post 2D sprites in 3D space? but I don't understand if the billboard method would split the content properly to ensure depth sorting of the quads.

Are there algorithms for basically projecting the image into the respective quads?

Addition Info (added 2012.03.06 @ 1124 GMT -6)

If you were to overlay a 3D box projected isometrically on top of a 2D isometric sprite (say a crate), the faces of the box (i.e. the top, left & right) should line up roughly with the perceived edges of the 2D sprite.  I want to chop up the 2D sprite along those edges and apply them to the 3 quads (again the top, left and right faces of the 3D cube).

I'd assume there is some pretty gnarly translations to skew the 2D content to fit that quads yet maintain their perspective when viewed via an iso camera in 3D.


texts: How to remove the old sprites in pygame and show them at a different location

texts:
I am trying to show the motion of some basketballs towards walle using the pygae sprites. The idea is that I don't know how to remove the old ones so they won't show. Is there a move method so that it would know it has to draw it again at the specified location?
I created a sprite class. Then I have a Character class that uses the sprite class and threads to calculate the intermediary coordinates for them. But I don't want them to show on the screen forever, like the pictures show.
Thanks!

 import pygame

 class CharacterSprite(pygame.sprite.Sprite):

   def __init__(self, location, image, surface):
       pygame.sprite.Sprite.__init__(self)
       self.image = pygame.image.load(image).convert_alpha()
       self.rect = self.image.get_rect()
       self.rect.center = location
       self.surface = surface

    def draw(self):
       self.surface.blit(self.image, self.rect)

   def update(self, location):
      self.rect.center = location
      self.draw()

import threading
import pygame
import os
from random import randint
from Sprites.CharacterSprite import CharacterSprite

LOCK = threading.Lock()

class StudentCharacter(threading.Thread):
   NRSTEPS = 3
   YPOS = 440
   TEACHERPOS = 40
   IMAGE_PATH = os.path.join('images', 'ball.png')

def __init__(self, screen, xpos, interval):
    threading.Thread.__init__(self)
    self.screen, self.xpos, self.ypos, self.interval = screen, xpos, self.YPOS, interval
    self.draw(self.xpos, self.ypos)
    self.configure()

def draw(self, x, y):
    self.circle = CharacterSprite([x, y], self.IMAGE_PATH, self.screen)
    self.circle.draw()

def configure(self):
    (left, right) = self.interval
    self.target = randint(left, right)
    xdif = self.target - self.xpos
    ydif = self.TEACHERPOS - self.ypos
    self.normal = {'x': int(xdif / self.NRSTEPS), 'y': int(ydif / self.NRSTEPS)}
    print self.target, self.normal['x'], self.normal['y']

def update(self):
    self.circle.update([self.xpos, self.ypos])

def run(self):
    i = 0
    while i < self.NRSTEPS:
        LOCK.acquire()
        pygame.time.wait(100)
        self.xpos += self.normal['x']
        self.ypos += self.normal['y']
        self.update()
        print self.xpos, self.ypos
        pygame.display.update()
        i += 1
        LOCK.release()
    print "Done"


texts: How can I make an object move in a certain direction depending on its spawning point?

texts:
I'm currently developing a 2D game and I couldn't find a way to figure this out. In the game, I have 4 different balls and 4 different spawning points. Every 2 seconds, a random ball spawns at a random spawning point.

What I want to achieve is, as I tried to describe above, lets say a ball spawns on right side, I want it to move towards left, if it spawns upside, I want it to go downwards etc.
Here is my spawner code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Game : MonoBehaviour {

    public Transform[] spawnPoints;
    public GameObject[] balls;

    public float timer = 2.0f;

    void Update()
    {
        timer -= Time.deltaTime;
        SpawnBalls ();
    }
    void SpawnBalls()
    {
        int spawnPoints_num = Random.Range (0, 4);
        int balls_num = Random.Range (0, 4);

        if (timer <= 0)
        {
        Instantiate (balls [balls_num], spawnPoints [spawnPoints_num].position, spawnPoints [spawnPoints_num].rotation);
        timer = 2.0f;
        }
    }
}

And here is my ball movement code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Balls : MonoBehaviour {

    public Game game;
    public float speed = 0.25f;

    void Start ()
    {
        game = FindObjectOfType<Game> ();
    }

    void Update ()
    {
    //Some if statement
    //transform.Translate (Vector3.left * Time.deltaTime * speed);
    //else if
    //transform.Translate (Vector3.up * Time.deltaTime * speed);
    //else if
    //transform.Translate (Vector3.right * Time.deltaTime * speed);
    //else if
    //transform.Translate (Vector3.down * Time.deltaTime * speed);
    }
}

I've tried giving spawnpoints tags and creating if statements with gameObject.tag and stuff but couldn't find a way to work it. How can I make it check which spawnpoint the ball spawned at so I can make it move accordingly?
Thanks for help.


texts: How do I start the process of looking for playtesters for an iOS game?

texts:
How does an independent developer typically go about finding a group of people to playtest their iOS game in 2013?

Is it through Reddit? College campuses? Steam Forums?

For example my game is targeted at males, ages 25-33 and the initial test I want to do on an iPad.


texts: Adding touch/click event to a bitmap in android

texts:
In my android game, there is a surfaceview which has 36 bitmaps drawn on it. I want to change the bitmaps when they are touched. Is there a way implement touch or click event to the bitmaps ?

Adding touch event to surfaceview and then to calculate the bitmap touched will be very tedious since there are 36 bitmaps.


texts: 3D model exported from Maya behaving weirdly

texts:
I have some 3-4 3D character models which are claimed to be exported with the same configuration from Maya by the 3d designers. Now, some of the models(animations) is working fine in Humanoid settings and not working in Generic mode and vice versa. The one which is working in Humanoid seems to have only one of its feet as crooked up. Though in maya, everything seems to work perfectly fine.

Now if there was some issue with the configurations while exporting, then it has to affect both its feet and not just one. I have also checked the T-Pose and automap settings in the Unity and everything seems to be fine.

Suppose for character A, all the animations work with Humanoid settings, then in Generic, for all animations it is kind of idle in a T-pose structure and do nothing not even simple walk animation.

I have been using Unity v5.0.1.

Please, if anyone could come up with any help would be highly appreciated.


texts: Multiple keypresses causing wierd results in SDL

texts:
I have been building a pong clone. I've been using a mixture of peoples different code to understand the way they structure their games as well as reading on game patterns. Currently I've gotten to draw a paddle on the screen and the player can move it with the keyboard no problem.

The issue comes when a player presses a button that is not 'Up' or 'Down'. For instance when the player holds the 'Up' key the paddle travels upwards, but if they simultaneously hold the 'Right' key it causes the paddle to fly downwards at a much greater speed.

My keyboard checking code is:

void GameLoop::Input(SDL_Event &ev)
{
    if (ev.type == SDL_KEYDOWN)
    {
        if (ev.key.keysym.scancode == SDL_SCANCODE_DOWN)
        {
            player1->IsMoving(true);
            player1->velocity = 10;
        }
        if (ev.key.keysym.scancode == SDL_SCANCODE_UP)
        {
            player1->IsMoving(true);
            player1->velocity = -10;
        }

    }

    else if (ev.type == SDL_KEYUP)
    {
        if (ev.key.keysym.scancode == SDL_SCANCODE_DOWN)
        {
            player1->IsMoving(false);
            player1->velocity = 0;
        }
        if (ev.key.keysym.scancode == SDL_SCANCODE_UP)
        {
            player1->IsMoving(false);
            player1->velocity = 0;
        }
    }
}

The GameLoop is ran within loop that is configured to run at 60FPS. You can see this in this code block here:

int main(int argc, char **argv){

    //Initialise the app and SDL
    App app(SDL_INIT_VIDEO);
    GameLoop game;

    double lastTime = 0.0, currentTime;

    SDL_Event e;

    while (app.isRunning())
    {
        if (SDL_PollEvent(&e))
        {
            if (e.type == SDL_QUIT)
            {
                app.exit();
            }
        }

        currentTime = SDL_GetTicks() / 1000.0;
        if (currentTime >= lastTime + 0.01666667)
        {
            game.Input(e);
            game.Update();
            game.Render();

            lastTime = currentTime;
        }

    }

    return 0;
}

This is the paddles update code:

void Paddle::Update()
{
    if(moving == true)
    {
        rect.y += velocity;
        velocity = 50;
    }

    X = rect.x;
    Y = rect.y;
}

I'm unsure of what is causing the paddle to behave so strangely. Any insight given into this problem or even just the way I've approached this problem would be appreciated.


texts:
I want to make play and pause buttons to play and pause sound and also I want it to play and pause animation ,how should I do that?

//function
 public void TogglePlay()
    {
        if (audio.isPlaying)
        {
            audio.Pause();
        }
        else
        {
            audio.Play();
        }
    }


texts:
Introduction:

I am working on a heat map made by Perlin Noise with the next result:

(Figure 1)

                  *(Red means really hot and light blue is colder)*

The algorithm identifies that mountains are colder at their top and plains vary between warm and hot(randomly, there is no physics behind).

QUESTION:

How can i do so that heat map i generated with Perlin Noise looks like this example:

(Figure 2)

where the temperature variations follows something like Earths equator.

My Ideas:

I thought about divide the map manually (from height to height2 is hot and so on...) but i do not like that idea as i want something more dynamic (temperatures may vary so does the heat map)

What i am asking?

Is there any better solution to this idea i had?

Thanks for your interest in this question.

EDIT:

With the code below i made possible the next thing:

public static Texture2D GetAirTemperature(int width, int height, Tiles[,] tiles)
{
    var texture = new Texture2D(width, height);
    var pixels = new Color[width * height];

    for (var x = 0; x < width; x++)
    {
        for (var y = 0; y < height; y++)
        {
            if (y <= 5 || y >= 95)
            {
                pixels[x + y * width] = Coldest;
            }
            else if (y <= 15 || y >= 85)
            {
                pixels[x + y * width] = Colder;
            }
            else if (y <= 30 || y >= 70)
            {
                pixels[x + y * width] = Warm;
            }
            else if (y <= 45 || y >= 55)
            {
                pixels[x + y * width] = Warmer;
            }
            else { pixels[x + y * width] = Warmest; }
        }
    }

    texture.SetPixels(pixels);
    texture.wrapMode = TextureWrapMode.Clamp;
    texture.Apply();
    return texture;
}

and obtaining the next result:

(Figure 3)

How i could multiply/modulate/something it by my Perlin noise so i get something irregular but looks a like Earths Equator?

Because you cannot do like Texture2D * Texture2D (multiply textures)

EDIT2:

What if, instead of using noise, i create my own 2D air temperature map as a starting point?
I mean, my own matrix [width*height].

Temperature will have the input given at the center of matrix (equator) and then, when update the temperature map (a cycle).

A cycle will go once in a while (periodically) to simulate temperature changes.

The input from the sun at the equator [(width/2)x(height/2)] will move outwards from the center into "north and south the matrix" (North is x, y < 50 && south is x,y > 50)

That means i have to check each row and number above and under the equator while maintaining energy conservation and other factors.

It is nice on paper but a hell in coding. Do you have any other idea to accomplish something similar to figure 3?


texts:
Why these numbers??
I have created a dynamic ubo and two objects, one for view and proj and the other for model.
Here I update the objects:
Render::UniformBufferObject ubo{};
        Render::UniformBufferObject2 ubo2{};

        ubo2.model = &model_transform.GetWorldMatrix();

        ubo.view =  &EditorCamera_transform.GetWorldMatrix().Inverse();

        ubo.proj = &current_camera->GetProjectionMatrix();

        // map memory without a staging buffer
        void* data;
        auto memory = uniform_buffer->get_ubo_memory();
        Render::VulkanMemoryAllocator::get_instance()->map_buffer_allocation(memory[current_image], &data);
        memcpy(data, &ubo, sizeof(ubo));
        memcpy(data, &ubo2, sizeof(ubo2));
        Render::VulkanMemoryAllocator::get_instance()->unmap_buffer_allocation(memory[current_image]);

Here binding and draw command:
std::array<uint32_t, 2> dynamicOffsets =
            { i * static_cast<uint32_t>(Render::StandardUniformBuffer::required_alignment(sizeof(Maths::Matrix4)*2)),
              i* static_cast<uint32_t>(Render::StandardUniformBuffer::required_alignment(sizeof(Maths::Matrix4)))
            };

            cmd.bindDescriptorSets(
                vk::PipelineBindPoint::eGraphics,
                *pipeline->get_pipeline_layout(),
                0,
                2,
                descriptor_set->get_descriptor_sets()->data(),
                2,
                dynamicOffsets.data());

            cmd.drawIndexed(static_cast<uint32_t>(index_buffer->get_primative_indices_size()), 1, 0, 0, 0);


texts: box2D and libgdx: Attach ParticleEffect to Body

texts:
Hello I am a newbie with libgdx, my question is: how could I add a Particleeffect to a Body that is moving? I searched about the matter and I didnt find anything related to it.

I have the following code to add my ball:

public Body createThrowedBall(float x, float y) {

    Gdx.app.log("createThrowedBall", "("+x+","+y+")");

    BodyDef ballDef = new BodyDef();
    ballDef.type = BodyType.DynamicBody;
    ballDef.position.set(x,y);

    CircleShape shape = new CircleShape();
    shape.setRadius(5.5f);

    FixtureDef fixtureDef= new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;
    fixtureDef.friction = 0f;
    fixtureDef.restitution = 0f;
    fixtureDef.filter.groupIndex = -1;

    Body body = world.createBody(ballDef);
    body.createFixture(fixtureDef);
    shape.dispose();

    // note the massive impulse vector

    body.applyLinearImpulse(new Vector2(0, 5500), new Vector2(x,camera.viewportHeight), false);

    return body;
}

That draws a simple circle shape that is throwed up. I want to add like a fire effect burning during the throw ( I did it with the Particle Editor) but I dont know how to attach it.


texts: trying to get an int grid of values from unity tilemap

texts:
I'm trying to get a 2 dimensional grid of values from a tilemap and found this which seems to do the trick:

_tileMap = gameObject.GetComponent<Tilemap>();

foreach (var position in _tileMap.cellBounds.allPositionsWithin)
{
    Debug.Log(gameObject.name + ": " + position);
    // TileBase tile = _tileMap.GetTile(position);
    // if(tile.name != null) Debug.Log(tile.name);
}

However, something strange happens as it produces two values, when I only have one tile on the tilemap and when I uncomment my .name log above it only works for the second value and errors for the first.

Any help of the best way of finding values from tilemaps would be great.


texts:
I have been working on a game for a while now, and it is going to be a TBS(Turn based strategy) in space.

And now I have come to the point where I am creating an AI for the game. I have no experience when it comes to designing AI's, the first one I ever made was based on random int's and getting the target out of an array.(not exactly a real AI)

On this topic I have a few questions:

How can an AI assess what is the best move to do next? Several units can move every turn.
How does a common AI consider what to do?(Example: Civilization, StarDrive 2, and similar)
How do I manage all the possible outcomes and the moves the AI can/should do?


texts: ECS multiple materials per mesh (sub-mesh)

texts:
In my toy engine I currently have a MeshComponent and a MaterialComponent.
psuedo:
struct MeshComponent
{
    Ptr<Mesh> Mesh;
};

struct MaterialComponent
{
    Ptr<Texture> DiffuseTexture;
    Ptr<Texture> NormalsTexture;
};

This is fine, for when a single mesh uses a single material.
pseudo:
Entity entity = CreateEntity();
AddComponentToEntity(entity, meshComponent);
AddComponentToEntity(entity, materialComponent);

But now I want to consider the concept of "sub-meshes" (regions of a mesh that are rendered with a different material, but each sub-mesh shares the parent vertex list). I don't want my Mesh class to know anything about materials, and vice-versa.
What good approaches are there for "joining" multiple MaterialComponent to a single MeshComponent?
I've considered having an entity for each sub-mesh, but that seems brittle (not to mention overkill, as I'm only interested in MaterialComponents).
pseudo:
struct MeshComponent
{
    Ptr<Mesh> Mesh;
    std::vector<Entity> SubMeshEntities; // Would need to ensure the indices match those of the sub-meshes
};

What other approaches are there?


texts: Matrix for transforming a square to a quadrilateral

texts:
I have a square of points {<0, 0, 0>, <6, 0, 0>, <6,0, 6>, <0,0,6>}
(The square is placed at the origin in the xz plane in opengl).

Want to apply a transformation/s on the square and make a quad whose points are {<-0.156712, -0.010205, 1.392891>, <-0.025491, -0.054014, 1.602598>,<0.097527, -0.026609, 1.470910>, <-0.033522, 0.014052, 1.301813>}

How would the transformation matrix be derived?


texts: Minecraft Forge modding 1.8 instance changing tool/armor material + color

texts: I am developing a minecraft mod in forge, and I need to find a way to create tools and armor where individual instances of items would have different tool material properties, armor material properties, and hues in how they are displayed. If you can offer help for any of those things, or for how to achieve these dynamic properties in general, I would be very appreciative.


texts: What techniques can I use to render very large numbers of objects more efficiently in OpenGL?

texts:
You can think of my application as drawing a very large ball-and-stick diagram (or graph).  At times, this graph can get very large, where the number of elements even outnumbers the pixels on the screen.  Currently I am simply passing all of my textures (as GL_POINTS) and lines to the graphics card using VBO's.

When the number of elements outnumbers the number of pixels, is this the most efficient way to do this?  Or should I do some calculations on the CPU side before handing everything over to the GPU?

If it matters, I do use GL_DEPTH_TEST and GL_ALPHA_TEST.  I do some alpha blending, but probably not enough to make a huge performance difference.

My scene can be static at times, but the user has control over a typical arc-ball camera and can pan, rotate, or zoom.  It is during these operations that performance degradation is noticeable.


texts:
I'm working on a script that uses raycasting from the camera's perspective to see what the player is looking at.  Pretty standard stuff.  The only question is, how to reliably find the camera?

Everything I've seen says you don't want to use Camera.main in Update() because performance, so instead you should call it once in Start() and cache it in a field.  And that's great, as long as you can guarantee that the main camera will never change.  But what if it does?

What I'd like is to have some sort of OnCameraUpdated event I can subscribe to that will let me know when the main camera has changed, but I don't see anything like that on the Camera class.  Is there any good way to find this out without polling for it?


texts: AS3 Air - Custom slider - limit drag position

texts:
I'm facing issues with finding the right solution for detecting and limiting the Sprite object "Knob" moved on y axis inside it's parent sprite "Frame", using FlashDevelop 5.
Using the code bellow I'm creating the frame on stage
private function init():void{
var frame: Frame = new Frame;
frame.x = 100;
frame.y = 100;
addChild(frame);
}

And in the Frame class, I create the child named "Knob" and add touch event listeners (with multitouch support, therefore using dictionary - Thanks to this post ):
public class Frame extends Sprite
    {
        public var knob: Knob;
        private var curTouchPoints:Dictionary = new Dictionary();

        public function Frame()
        {
            addEventListener(Event.ADDED_TO_STAGE, addListeners);
            init();
        }

        private function addListeners(event:Event):void
        {
            stage.addEventListener(TouchEvent.TOUCH_MOVE, touchMove);
        }

        private function touchStart(e:TouchEvent):void
        {
        curTouchPoints[e.touchPointID] = {obj: e.currentTarget, offsetX: e.localX, offsetY: e.localY}; //store the current object in the dictionary
        trace(e.currentTarget)
        e.currentTarget.addEventListener(TouchEvent.TOUCH_END,touchEnd);
        }

        private function touchMove(e:TouchEvent):void
        {
          if (curTouchPoints[e.touchPointID]) {
          DisplayObject(curTouchPoints[e.touchPointID].obj).y = e.stageY-this.y - curTouchPoints[e.touchPointID].offsetY;
        }
        }

        private function touchEnd(e:TouchEvent):void
        {
        delete curTouchPoints[e.touchPointID];
        e.currentTarget.removeEventListener(TouchEvent.TOUCH_END, touchEnd);
        }

        private function init():void
        {
            this.graphics.beginFill(0xffffff, 1);
            this.graphics.lineStyle(1, 0x000000, 1);
            this.graphics.drawRect(0, 0, 120, 600);
            this.graphics.endFill();

            knob = new Knob;
            knob.x = 20;
            knob.y = 20;
            knob.addEventListener(TouchEvent.TOUCH_BEGIN, touchStart);
            addChild(knob);
        }

    }

The Knob class is simple sprite object:
public function FaderKnob()
        {
            this.graphics.beginFill(0x000000, 1);
            this.graphics.lineStyle(1, 0x000000, 1);
            this.graphics.drawRect(0, 0, 80, 80);
            this.graphics.endFill();
        }

With the current code, it all works as expected except that I want to limit the Knob to never leave it's parent - Frame! Means, it's top coordinate will be 0, and it's bottom should be "Frame.heigth - Knob.height", so it stays fully inside.
I've been searching for the HitTestObject, but that doesn't do the work as the Knob is in the Frame all the time... :/
If it matters: The window is/will be transparent with chroma:none, and both, frame and knob should have alpha 0 (whole app is supposed to be fully transparent, to implement multitouch support on non-multitouch game)
This is done fine now, just mentioning if it might matter for some HitTest procedures based on pixels or something.. I'm fairly new to AS3 and Air so please bare with me :-)
As a side note, I'd need to read the 8-bit "value" (0-255) based on the knob's position in its parent, which I have a slight idea of how to do, but I'm sure there's an easier way than what I imagined.. :)


texts: Unity 3D - Rotate towards object with random offsets

texts:
Title is a little confusing, but let me explain:

I want to make the enemies look at the player, and shoot at him, with random precision, meaning that one time the enemy will shoot a little bit to the left of the player, next time a little bit to the right of him, and sometimes exactly at him.

Currently I have this scene:

The turret rotates, and when the green direction spots the player, it shoots a bullet facing the player (the green arrow).

Now I need where the rotation is passed for the Instantiate, to have some random precision, and I don't know how to do it. Here's what I have so far

Vector3 pos = new Vector3(firingPoint.transform.position.x, firingPoint.transform.position.y, firingPoint.transform.position.z);

float playerX = playerObject.transform.position.x;
float playerY = playerObject.transform.position.y;
float playerZ = playerObject.transform.position.z;

float randomX = Random.Range(playerX - 1f, playerX + 1f);
float randomY = Random.Range(playerY - 1f, playerY + 1f);
float randomZ = Random.Range(playerZ - 1f, playerZ + 1f);

Quaternion aimPrecision = Quaternion.LookRotation(new Vector3(randomX, randomY , randomZ));

Instantiate(bulletPrefab, pos, aimPrecision);

How can I do this?

EDIT: Right now, the enemy shoots like this:

but never towards me, or backwards


texts: Unity ball hitting paddle not reflecting right away

texts:
After the ball hits the paddle it continues for a frame or two in the physics, reflected direction, then my onCollisionEnter2D function runs and changes the velocity. At least, that's what it seems like. I'm a noob with Unity so I must be misunderstanding something.

https://streamable.com/ac2gg

if (other.gameObject.CompareTag("Paddle"))
    {
        float dist = ballRb.transform.position.x - paddleRb.transform.position.x;

        if (dist > 0)
        {
            print("right");
            ballRb.velocity = new Vector2(4, speedY);
        }
        else
        {
            print("left");
            ballRb.velocity = new Vector2(-4, speedY);
        }
    }

Thoughts on why there's a stutter after a redirection? I slowed it down so you can see better what's happening.


texts:
Heres a picture that explains better than my words can

For rotating an object I'm using quaternions.
    CreateFromAxisAngle(vector3.Right,yaw)

Maybe this isn't how I should be doing it but I also keep my yaw as radians that
are always between 0 and 360;more or less than 0 or 360 puts it at 0 or 360 respectively.

(object is build up of vertices and indices)

I can rotate it no problem. Move it all about.
But what I really want to do is to find how much I should alter the
yaw so that the my models right vector will sync up with the line
I can draw between the objects center and the camera's position(y is always 0).

Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction.

Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left.

I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light?


texts: How to implement large data files without using up a lot of space at runtime?

texts:
Say I have a bunch of images that I want to use with my game; I want the image files to be external, so overall I have the game's executable and a directory full of images. Let's say there are 100+ images and the size of the directory is ~500 MB.

I don't want the player to easily access these image files, so rather than having a directory containing 100+ individual files, I pack all the images into one large 500 MB file: "images.big"

With compression, I can reduce the size of "images.big" to ~50 MB. So all the player needs to download is the executable and a 50 MB file.

The problem is when I want to display the images in the game, it has to decompress "images.big" which creates a temporary 500 MB file and then it has to unpack all the images into a temporary directory (taking up another 500 MB) so it can display them based on filename. The game's directory goes from 50 MB to 1 GB, and on top of that the player can easily access the image files while the game is running.

Is there a much better way to go about this, or is it really a non-issue for a game to be creating such large temporary files/directories at runtime?


texts: Physics fixed time step with client/server games

texts:
I'm trying to make a 2D platforming multiplayer game with client/server system.
I want to use Node.js and Phaser for the display.

I read a lot about fixedTimeStep : http://gafferongames.com/game-physics/fix-your-timestep/

Do you think it's viable with JS (and Phaser)?
Do you think it's possible to decouple update() and render() loop with a single-threaded language like JS?


texts: How do I avoid Race Conditions in UnrealScript?

texts:
I'm trying to create a pseudo turn based battle system in the Unreal Engine (think Final Fantasy style).

I'm trying to avoid the Enemies and the players attacking while another animation is in progress. I thought the most simple solution is to have a flag somewhere that the player controllers check before starting an animation, and set it to a value before they start, and then reset it when they've finished.

However, I could see this leading to race conditions if two controllers (AI or player) try to access the variable at the same time, then both start their animations.

If I was writing this in Java I'd obviously use synchronized methods, but I haven't come across anything like that in UnrealScript. Is there another way to avoid this? Its probably not the end of the world, as its a pretty unlikely occurance, but I'd like to try and avoid it completely if possible.


texts: How do I handle moving platforms in a platform game?

texts: I don't want to use box2d or anything, I just want simple moving platforms (up-down, left-right, diagonal and circular paths). My question is to handle the update order / control hierarchy so that the player stays fixed to the platform solidly, without bouncing or wobbling?


texts: Drawing sprites to a permanent Texture2d using Monogame / XNA

texts:
I'm working with Monogame to do a 2d sprite engine.  I've gotten it work pretty well where I can move lots of sprites around the screen with the effects and positions that I want.

Last night I tried to add a feature and I can't quite get it to work right.
I'm trying to create permanent trails that the moving sprites can leave behind.  So I have a mostly transparent PNG with some white lines on it called "streak".
The idea is that I set up a new Texture2d surface (called streakoverlay) and I draw the streaks on to it.

I switch back to the back buffer and draw: The background, the streakoverlay, and finally the sprite on top of it.  The streaks should build up over time.
It almost works, but the trouble I have is that streakOverlay seems to clear itself every time.  How I'd like it to behave would be the same behaviour as having the graphics display without this line "GraphicsDevice.Clear(Color.White);" - everything would just pile up in it.

Instead it resets back to the Purple transparent color that is the default for that texture.
Any suggestions?  Here's the core piece of the rendering engine:

GraphicsDeviceManager graphics;
RenderTarget2D streakOverlay;
SpriteBatch spriteBatch;

private Texture2D bkg;
private Texture2D prototype;
private Texture2D streak;

//Initialize
graphics = new GraphicsDeviceManager(this);
GraphicsDevice.Clear(Color.Transparent);
streakOverlay = new RenderTarget2D(GraphicsDevice, 200,200);

//Load Content
bkg = Content.Load<Texture2D>("bkg"); //Background image
prototype = Content.Load<Texture2D>("prototype"); //Prototype sprite that moves around
streak = Content.Load<Texture2D>("blueStreak"); //Trails being left by Prototype sprite

graphics.GraphicsDevice.SetRenderTarget(streakOverlay);
GraphicsDevice.Clear(Color.Transparent); //Attempt to make the streakoverlay is fully transparent.
graphics.GraphicsDevice.SetRenderTarget(null);

//Draw
Random r = new Random();
graphics.GraphicsDevice.SetRenderTarget(streakOverlay); //Switch to drawing to the streakoverlay

spriteBatch.Begin();
//Draw some streaks that should accumulate
spriteBatch.Draw(streak, new Vector2(r.Next(0, 200), r.Next(0, 200)), null, Color.White, 0f, new Vector2(25, 25), 1f, SpriteEffects.None, 1f);
spriteBatch.End();

//Switch back to drawing on the back buffer.
graphics.GraphicsDevice.SetRenderTarget(null);

spriteBatch.Begin();
spriteBatch.Draw(bkg, new Rectangle(0, 0, 2000, 2000), Color.White);    //Draw our background
spriteBatch.Draw(streakOverlay, new Vector2(0, 0), Color.White); //Put the overlay on top of it
spriteBatch.Draw(prototype, new Vector2(_spritePrototype.getX, _spritePrototype.getY), null, Color.White, DegreeToRadian(rotationSprite), new Vector2(25, 25), .5f, SpriteEffects.None, 0f); //Draw the sprite that's moving around.
spriteBatch.End();

base.Draw(gameTime);


texts:
I'm trying to make text have a fixed position in world space and be overlayed in screen space at the same time.

I have text in canvas with "Screen Space - Overlay" which covers my text located in canvas (world space).

What should I do? Is this a dead end? Please comment if you didn't understand (I know it's hard to get)


texts: How to best simulate the space in a boxing game to account for footwork and angles?

texts:
When trying to prototype a (top-down, so far) boxing simulation I've run into a huge roadblock with trying to set the space in which the boxers will fight, because it's important for the fighters' reach to be a factor in setting the distance of the fight, which is easier in a continuous space. On the other hand, they should also be able to cut angles where the opponent is out of position when compared to themselves (like Tyson did below), which would probably be easier to represent in a discrete space, like a hex, but the rotation would be very rigid. The difference between stances would also be more difficult to represent in a discrete gamespace, since foot position is entirely different, as well as the reach.

I've been coding this in Godot, so it would not be that much more difficult to do a continuous space and use their signals and collision shapes to do it, my only concern being the computational cost of actions would be raised with the amount of positions available, so I'd rather have an abstraction.
Is there any obvious solution I'm missing? Some way both things can be represented (in a way an AI can easily interact with) without unnecessary granularity? Or a way to do it in a continuous space that wouldn't greatly increase computational overhead with the massive array of new positional possibilities?


texts: Sprite framework binding multiple textures

texts:
In an attempt to batch render as many quads (sprites) as possible, I'm instance rendering a single unit-sized quad and passing in a buffer of per-instance data that includes width/height, texture coordinates, color, texture Id, etc.

Offline, I have a tool that constructs texture atlases based on any particular sprite animation, so the output is flexible in terms of texture atlas width/height, which sprites reference which texture atlas, and so on.

The end result is that I may have many texture atlases, and sprites which reference any one of those atlases for their current frame.

I need a robust solution that'll allow me to draw these sprites in any order while reducing texture binding as much as possible. After some research there are two options:

combine multiple 2D textures into a 2D array texture (up to GL_MAX_ARRAY_TEXTURE_LAYERS_EXT)
bind multiple textures in array of samplers (up to MAX_TEXTURE_IMAGE_UNITS)

The first solution I believe requires all textures to be the same height/width.
The second solution seems to have a limitation that requires a constant index to access the array of samplers in the fragment shader.

I think I want to go with the second solution, but I'm worried I won't be able to properly write a fragment shader if I have to use a constant index, as I'd be getting the index via per-instance data input.

Are my above suspicions correct? Is there a known work-a-round for the second solution? Or is there a better way to do this than what I presented.


texts:
Apologies if this is a reiteration, as I couldn't find another discussion of this over the past couple days.

Issue:
I'm using libgdx and box2d, and I'm currently updating the sprite's position to the body's current position every render call. Using a debugRenderer to see the bodies, I see that there is fairly noticeable lag between the movement/position of the body and the sprite that is being moved relative to it.

Question:
Is this lag normal, possibly to perform collisions ahead of time? If not, should I be manipulating/relating the positions differently?

Thanks in advance!

[Solution]
This was a coding error on my part. Pointed out by a good reply below, I was updating the position of the sprite relative to the body and then stepping the physics. Thus never actually setting the sprite to the body's CURRENT position. Thanks!


texts:
I'm having trouble with my character on a 2.5D platformer. The character get stuck if it collides without reaching the platform's top. Here is a gif showing it: http://i.imgur.com/jmZ6O1K.gifv

Both colliders (platform and character) has a physics material with no friction (or minimum). So I don't know why is this happening.

Character Collider

Physic Material


texts:
I have really throughly searched the net and could not find any solution for this so I ask for help here.

Anyway, I have this datablock in datablocks.cs:

    datablock t2dSceneObjectDatablock(EnemyShipConfig)
{
   canSaveDynamicFields = "1";
   Layer = "3";
   size = "64 64";
   CollisionActiveSend = "1";
   CollisionActiveReceive = "1";
   CollisionCallback = true;
   CollisionLayers = "3";
   CollisionDetectionMode = "POLYGON";
   CollisionPolyList = "0.00 -0.791 0.756 0.751 -0.746 0.732";
   UsesPhysics = "0";
   Rotation = "-90";
   WorldLimitMode = "KILL";
   WorldLimitMax = "880 360";
   WorldLimitMin = "-765 -436";

   minFireRate = "2000";
   maxFireRate = "1200";
   laserSpeed  = "800";
   minSpeed    = "100";
   maxSpeed    = "150";
};

This is an exact reproduction of an object that I have manually edited in the editor. So far, I just used clone() to get as many enemies as I need, while it was out of sight. It is a r-type style shooter, so I need a variable amount of enemies. Since clone() spams my log, I decided to use datablocks, since it is also more flexible.

That's what I get when I use clone():

  Con::execute - 0 has no namespace: onRemoveFromScene

However, once spawning begins, my game freezes and crashes:

    function SpawnEnemy()
{
    //%spawnedEnemy = EnemyShipMaster.clone(true);
    %spawnedEnemy = new t2dStaticSprite()
    {
       class         = "EnemyShip";
       sceneGraph    = $global_sceneGraph;
       datablock     = "EnemyShipConfig";
       imageMap      = "starshipImageMap";
       layer = 3;
    };

    %speed  = getRandom(%spawnedEnemy.minSpeed, %spawnedEnemy.maxSpeed);
    %y      = getRandom(-320, 320);

    // Set Properties
    %spawnedEnemy.setPositionX(700);
    %spawnedEnemy.setPositionY(%y);
    %spawnedEnemy.setVisible(true);
    %spawnedEnemy.setLinearVelocityX( -%speed );
    %spawnedEnemy.setTimerOn( getRandom( %spawnedEnemy.maxFireRate, %spawnedEnemy.minFireRate ) );
}

// Definition of $global_sceneGraph from game.cs:
$global_sceneGraph = sceneWindow2D.loadLevel(%level);

As I said, it works fine when I use clone() (which is commented out here), but my log gets spammed. I really hope someone can shed some light for me, this is driving me crazy.


texts: Collision detection of cicle and rectangle

texts:
How to find the collision detection of a moving rectangle on circular object?
Here i have tried to junp rectangular object but the collision detection of a small rectangular object while jumping doesnt have smooth collision detection? Can anyone please help me ?


texts: HLSL identity matrix multiplication not producing identical output

texts:
I'm debugging my very simple shader and it's led me to a point where, as a quick test, I'm performing a multiplication of my position vector with an identity matrix. If I don't perform this multiplication, my position is preserved and I get a nice-looking quad in the middle of the screen, as expected. If I multiply with an identity matrix, my quad goes away, leaving only the background. I'm sure I'm missing something, or doing something stupid (or both), but I have no idea what that is. My code is below:

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

struct VIn
{
    float4 position: POSITION0;
    float4 color: COLOR0;
    float2 texcoord: TEXCOORD0;
    float2 pad: PADDING0;
    matrix translate: CUSTOM0;
};

matrix Identity =
{
    { 1, 0, 0, 0 },
    { 0, 1, 0, 0 },
    { 0, 0, 1, 0 },
    { 0, 0, 0, 1 }
};

VOut VSMain(VIn input)
{
    VOut output;
    float4 pos = float4(input.position.x / 4, input.position.y / 4, 0.0, 1.0);
    matrix trans = Identity;
    pos = mul(pos, trans); // <-- THIS LINE HERE DOESN'T DO WHAT I EXPECT
    output.position = pos;
    output.color = input.color;
    return output;
}

The line marked above should produce identical output to the pos input, but it does not.


texts:
I use top down 60 degree tilted camera and want move always visually straight directions relative to screen (up, down, left, right). When object is near screen edges it starts moving diagonally (visually) probably because of camera tilt.

I tried with WorldToViewportPoint / ViewportPointToRay but it doesnt work exactly because even when there is no input, conversion to viewport and back to world same value sometimes gives slighltly offset from start position.

float delta = Time.deltaTime;

float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");

Vector3 view = MainCamera.WorldToViewportPoint(transform.position);

view.x = (h > 0) ? 1 : (h < 0) ? 0 : view.x;
view.y = (v > 0) ? 1 : (v < 0) ? 0 : view.y;

Ray ray = MainCamera.ViewportPointToRay(view);

RaycastHit hit;

Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << 15); // 15 - ground plane layer

Vector3 world = new Vector3(hit.point.x, transform.position.y, hit.point.z);

Vector3 dir = (world - transform.position).normalized;

transform.position += dir * Speed * delta;


texts: Why no night sky with realistic star constellations?

texts:
As an amateur stargazer I noticed that many games which have night scenarios use textures for the night sky where the stars seem to be arranged entirely randomly. It seems like they were created by an artist from scratch without looking at a star chart. Why don't they use a night sky texture where the stars are arranged like on the real night sky, so you can make out well-known constellations?

Games which take place in a fantasy or science fiction scenario are obviously excused, but why do games which take place on earth spend so much work on realism, but neglect this one aspect, even though there are plenty of public domain resources which could be used to create a realistic night sky?


texts: UNITY : how to pause baking and quit project?

texts:
How to pause the lighting bake and quit the project ? so when i re-open the scene it will continue baking without have to start the bake from beginning ?
I need to take a break to do other job on my computer, because after i turn on 'auto generate' , the baking takes very very long. I want to quit unity and continue later.
Right now if i reopen the project , it will bake from start again.
Thanks


texts: What's the size of library in unity for android?

texts:
In unity3d what is the size of library compiled into apk.
Is that affect when i make game without any physics(2d or 3d) or when making 2d or 3d game.


texts: Audio Clip not working on Collision when destroying an object

texts:
So I made a game where you shoot a laser and if it hits the enemy it makes an explosion sound and destroys the enemy. The only thing is whenever I try to get the audio to play it doesn't which I assume is caused by the enemy being destroyed. I have tried to use the Play() methods and PlayOneShot() methods but they both don't seem to help me out.

This is my current code:

public AudioClip explosion;
public AudioSource explosionAudioSource;

public void OnTriggerEnter2D(Collider2D other)
    {

    void Start() {
    explosionAudioSource = GetComponent<AudioSource>();
    }
        if (this.tag == "Enemy" && other.tag == "Laser")
        {
            explosionAudioSource.PlayOneShot(explosion);
            Destroy(other.gameObject);
            Instantiate(enemyExplosion, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
            Destroy(this.gameObject);
            uiManager.UpdateScore();
        }

Thanks!


texts: Single handler vs multiple handlers for the Command Pattern

texts:
I'll be soon implementing for the first time a Command pattern to catch general events about the world of the game I'm developing

Since I haven't found much info about this particular issue, I'm asking if it makes more sense to have a single 'catch-all' class which will eventually process any type of event or to offload events to different types of Queue

e.g. player related Commands will be offloaded to the Player class, enemies related commands will be offloaded to the Enemies class, and world/terrain related commands (such as chunk creation) will be handled by WorldGen

Normally, this would break the idea of having a 'receiver' object as a constructor parameter of an instance of a Command, but does having just a single 'catch-all' class more maintainable than partitioning the command handlers?

Is it maintainable in a convoluted game to have just a single catch-all class to execute every type of Command? Wouldn't it be easier to optimize the usage of more threads by having different command handlers?


texts:
What's the best way to make a character selector similar to DOTA 2 game, but instead of having an unique animation for the hero it just displays the sprite of the character, the game is 2D.

public GameObject[] gCharacters;
private float[] characterScales;
public GameObject Image;
int i = -600;
public Sprite sprite;

void Start()
{
    characterScales = new float[gCharacters.Length];
    for (int x = 1; x <= gCharacters.Length; x++)
    {
        GameObject inst = Instantiate(Image, Image.transform.position, Image.transform.rotation) as GameObject;
        inst.GetComponent<RectTransform>().position = new Vector2(gameObject.GetComponent<RectTransform>().position.x + i, gameObject.GetComponent<RectTransform>().position.y);
        inst.transform.parent = transform;
        sprite = gCharacters[2].GetComponent<SpriteRenderer>().sprite;
        Image.GetComponent<Image>().overrideSprite = sprite;
        i += 200;
    }
}

For the sprites to be displayed which is my main goal here I've used the IMAGE UI.


texts:
I'm completely new to gamedev and want to learn how to design good UI for a city-building game (like SimCity).

What books and other materials can I read in order to learn it?


texts: Automatically triggering standard spaceship controls to stop its motion

texts:
I have been working on a 2D top-down space strategy/shooting game. Right now it is only in the prototyping stage (I have gotten basic movement) but now I am trying to write a function that will stop the ship based on it's velocity. This is being written in Lua, using the Love2D engine.

My code is as follows (note- object.dx is the x-velocity, object.dy is the y-velocity, object.acc is the acceleration, and object.r is the rotation in radians):

function stopMoving(object, dt)
    local targetr = math.atan2(object.dy, object.dx)
    if targetr == object.r + math.pi then
        local currentspeed = math.sqrt(object.dx*object.dx+object.dy*object.dy)
        if currentspeed ~= 0 then
            object.dx = object.dx + object.acc*dt*math.cos(object.r)
            object.dy = object.dy + object.acc*dt*math.sin(object.r)
        end
    else
        if (targetr - object.r) >= math.pi then
            object.r = object.r - object.turnspeed*dt
        else
            object.r = object.r + object.turnspeed*dt
        end
    end
end

It is implemented in the update function as:

if love.keyboard.isDown("backspace") then
    stopMoving(player, dt)
end

The problem is that when I am holding down backspace, it spins the player clockwise (though I am trying to have it go the direction that would be the most efficient at getting to the angle it would have to be) and then it never starts to accelerate the player in the direction opposite to it's velocity.

What should I change in this code to get that to work?

EDIT :

I'm not trying to just stop the player in place, I'm trying to get it to use it's normal commands to neutralize it's existing velocity.

I also changed math.atan to math.atan2, apparently it's better. I noticed no difference when running it, though.


texts:
I'm new to Unity, but not programming in general. I have a turn based RPG type game and I'm wondering if anyone has comments/thoughts/ideas on the below structure that I'm thinking about for this system. The main idea is that in a file I save what actors/characters have what abilities by name. The abilities have a Do() function that does the actual ability sequence (since it's turn based the abilities are sequential in nature. jump here, do this, jump back, or spin, then move here, then here, then here, then back in the case of a whirlwind ability). Is adding the ability as a component the right thing to do? The abilities work on the game object and it seems deriving them from MonoBehavior gives you a lot of functionality to work on the game object so it seemed like the right thing to do, but I'm not 100% sure.

class Actor : Monobehavior{
    private List<Ability> abilities;
    public string name;

    void Start(){
        // read json file to populate the abilities this actor has based on it's name
        // but until then the basic idea is below
        var strike = gameobject.AddComponent<MeleeStrike>() as Ability;
        strike.Owner = this;

        abilities.Add(strike);
    }
}

interface IAbility{
    IEnumerable Do(Actor target);
}

class Ability : Monobehavior, IAbility{
    Actor owner;
}

class MeleeStrike : Ability{
    // this function will be called as a coroutine so we can do the sequence
    // that is this ability
    public IEnumerable Do(Actor target){
        // jump in front of our target
        Helper.JumpToPosition(target);

        // wait .5 seconds

        // play strike animation which will have event on hit to play sounds/effects/etc

        // wait .5 seconds

        // jump back to our position
        Helper.JumpToPosition(owner);
    }
}


texts: Random Placement of Objects on a Tilemap

texts:
I have read many topics on random world generation on this site and others, and I roughly understand most of it. What I can't see is how to randomly place objects on the generated tile map I get. Say I want to generate a forest. How would I go about doing this? I have tried studying other people's code. I delved into Notch's Minicraft to look at how it generates its random worlds.

I have identified this part of the code that generates trees for example.

for (int i = 0; i < w * h / 400; i++) {
        int x = random.nextInt(w);
        int y = random.nextInt(h);
        for (int j = 0; j < 200; j++) {
            int xx = x + random.nextInt(15) - random.nextInt(15);
            int yy = y + random.nextInt(15) - random.nextInt(15);
            if (xx >= 0 && yy >= 0 && xx < w && yy < h) {
                if (map[xx + yy * w] == Tile.grass.id) {
                    map[xx + yy * w] = Tile.tree.id;
                }
            }
        }
    }

However, this just confuses me. I need to be able to see how this code translates into spread out trees. There is also code for generating the desert.

for (int i = 0; i < w * h / 2800; i++) {
        int xs = random.nextInt(w);
        int ys = random.nextInt(h);
        for (int k = 0; k < 10; k++) {
            int x = xs + random.nextInt(21) - 10;
            int y = ys + random.nextInt(21) - 10;
            for (int j = 0; j < 100; j++) {
                int xo = x + random.nextInt(5) - random.nextInt(5);
                int yo = y + random.nextInt(5) - random.nextInt(5);
                for (int yy = yo - 1; yy <= yo + 1; yy++)
                    for (int xx = xo - 1; xx <= xo + 1; xx++)
                        if (xx >= 0 && yy >= 0 && xx < w && yy < h) {
                            if (map[xx + yy * w] == Tile.grass.id) {
                                map[xx + yy * w] = Tile.sand.id;
                            }
                        }
            }
        }
    }

Is this just way over my head or is there some kind of algorithm that I'm missing here?


texts: Circle vs Edge collision detection / resolution

texts:
I made a javascript class Ball.js that handles physics interactions betweens balls as well as painting.
In the v1.0, the ball vs ball collision detection and resolution is well handled.

In the next version (v2), I'm trying to add edgeCollision handling. I'm having some problems, maybe you will be able to help me.

All the v2 branch source code is on github repository : https://github.com/topheman/Ball.js/tree/v2

The v2 demos (where you can see the bug I will be talking about) : http://labs.topheman.com/Ball-v2/#help

As you will see on the demo, I have two major problems that I'm having a really hard time to solve on Ball.js :

method resolveEdgeCollision : bounce angle is inconsistent
method checkEdgeCollision : if the ball's velocity (the length that it runs each frame) is higher than its diameter, eventually, it will pass through an edge, without triggering any collision

Any Ideas ?...


texts: What is the difference between body transform and root transform

texts: I am learning about Root animation and here come two terms, one is root transform and Body transform. As name suggests that body transform is the character body but what is root transform? and what is the Root transform rotation based upon body orientation, Feet, center of mass or original.


texts:
I'm working on a networked multiplayer game, initially for iOS.

Even with TCP_NODELAY there are large fluctuations in latency. I can't be sure of the reason, but I would not be surprised if it was resends on packet loss due to flaky connections.

Having done no real life server work with UDP as opposed to TCP (which I have lots of experience with), I wonder if there are any significant gains to trying a UDP-based architecture.

Client packets are typically only a few bytes, sent rarely, except when moving, when the player might issue 2-8 commands/s. Server packets are slightly larger and mostly sent as response to a client command.

Connections need to be reliable and ordered.

ADDITIONAL INFO

Very early on I did some exploratory tests with TCP versus UDP. I would run connections Phone -> 3G -> External static IP of router -> Wifi -> Development computer and Phone -> Wifi -> Router -> Wifi -> Development computer.

What I wanted to improve was mainly the very uneven lag one would experience moving around on the map with a non-local connection.

Obviously starting animations can help, but there are (rare but valid) reasons why a move command might be rejected that the client have no way to predict. In addition, much data is hidden from the client, which again gives very little room for predictive responses.

Anyway, my results was the UDP and TCP gave pretty much the same average latency when sending data.

What I didn't look at was the actual spread - for example the maximum TCP latency in face of packet loss. I would have have needed to do some packet recovery mechanism in UDP to figure out if UDP could do better.

So again the results I see today with TCP is that usually it works fine, then suddenly a slowdown and a burst of movement as all the other buffered packets are more or less executed at the same time.