texts: What is the correct formula for penalty forces?

texts:
I am trying to add penalty forces between two hard body objects, so when they collide they move in a realistic way. What I have so far is this:
var totalMass = aMass + bMass;
var temp = (aMass / totalMass * aVelocity) + (bMass / totalMass * bVelocity);
newVelocityB = (bMass / totalMass * bVelocity) + (aMass / totalMass * aVelocity);
newVelocityA = temp;

Originally I thought this was correct and it seems to work for the most part. However, this doesn't seem to be flawless. For example, if the collided object is a vertical wall (represented with a mass of infinity), the wall's velocity of (0,0) will be the final result. So, for an object moving diagonally with a velocity of (10,10) and hitting the wall, will result in a velocity of (0,0). In my case I would expect that the y component of the velocity remains 10, and it keeps sliding up the wall.
Can anyone tell me if I'm on the right path, and how I can modify my formula to make sure that the y-velocity does not become 0?
I have considered that the collision normal of the wall could be important (in this example [-1, 0]), or the perpendicular of the normal, however I still have not figured out how to apply it in this formula. Multiplying by the perpendicular of the normal was my first idea, but this isn't the correct answer.


texts:
I am developing a simple Golf game as shown in the below image.

I am facing below issues:

Even if I apply small amount of force, the ball continuous move along the grass? Grass friction is not stopping the ball.
Sometimes, the ball speed is increased after colliding with the walls instead the ball speed should decreased after collision with the walls. The walls are having box collider.
Sometimes, the ball reverses its direction after colliding with walls.

Code:

Physics properties of the ball:

 ball.physicsBody.affectedByGravity = true;
 ball.physicsBody.mass = 0.0450;
 ball.physicsBody.restitution = 0.8;
 ball.physicsBody.friction = 0.3;
 ball.physicsBody.allowsResting = true;

Physics properties of the grass:

golf.physicsBody.friction = 0.8;

Physics properties of the walls:

 leftWall.physicsBody.friction = 0;
 leftWall.physicsBody.restitution = 0.8;

I have set the physics world gravity value to -9.8.

I am looking for suggestions to fix the above listed issue. Thank you.


texts: Are Anaglyph 3D shaders used in game engines?

texts:
I have always wanted to put on the "3d glasses" and instead of watching a 3d movie, go to my pc and play a game in real 3D. Has anyone ever tried creating a Real 3D game? Are there any shaders that would allow creating Anaglyph 3D effect in real time? How do they work? (If they exist)

  http://en.wikipedia.org/wiki/Anaglyph_3D


texts: I want my game to be user-translated friendly.I put .text file to Data folder from where strings will be read. What is Editor alternative for data folder ? Also i know compiler ignore some files, how i can tell compiler to include this one ? thanks.


texts: How big can a background file in Unity be?

texts:
I want to start a new 2D top-down project in Unity and want to figure out how to organize my background (one big file or a lot of files joined together).

So how big can a background file get in Unity?

The target platform is Windows.


texts:
I'm trying to implement a roguelike movement system for my game. I'm using the ECS architecture.
The requirements are:

entities will have a mass, on which should slow down the entity
movement accordingly. fatty ones move slower
there will have different terrains, that should apply different
friction types, eg: ice will decelerate the entity slower; a
quicksand will almost stop the entity immediately and so on.

[optionally]

there will have different weathers that should also impact on the
entity movement, eg: sandstorm would push the entity to it's
direction; rains will diminish the friction coefficient a little bit
etc...

If the two first requirements are solved, the third will probably be as well, I think.
How would you do this?


texts: How to Enable canvas with Event during a animation clip

texts:
I want to enable a canvas while an animation clip is playing, I used animation Event and call the following script to enable the canvas, but the editor does not recognize any game object.

How a canvas can be enabled?

public void SetActiveTrue(GameObject game_object)
{
    game_object.SetActive(true);
}


texts: How to check what part of an gameobject is seen by a camera?

texts:
Could anyone please give me a hint on how to determine how much of an object is seen by a camera. There have to be a threshold value (e.g. 30% of an object is seen). If value is below the threshold then I don't cast rays otherwise I will do.
Now I am using WorldToViewPoint-function w.r.t. center of an object, but it doesn't working properly in my view.


texts:
I need suggestions for the best method of acheiving what I am trying to do:

-Using either OpenGL ES 1.x or 2.x

I need to pass a bunch of vertices to the GPU. Each one has 3 attributes: Position, Color, and Texture coords.

The vertices form quads, which share vertices. The shared vertices have both position and color attributes in common, but texcoords are not shared because each quad is textured with a 'tile' from a texture atlas.

I already know that it is not possible to use separate indices for a glDrawElements() call, so does that mean I can only use indexing for individual quads(specify 4 unique vertices per quad)? .. or is there any better solution?


texts:
I've seen a couple of examples of some game balancing techniques in books yet they are not comprehensive and not particularly aimed at MMORPGs but I'm looking for practical examples of game balancing techniques for MMORPGs. I am interested to know if anyone has documented the techniques used in popular games with proven success in this area. Ideally, any resource would cover most common types of stats and include layman mathematical models or techniques used to balance game mechanics found in advanced MMORPGs (I know it's a cliché, but WoW style)

Any help would be great!


texts: How to detect syntax error in unity shader scripting

texts:
Hi. I'm following shader scripting tutorial and I often make syntax mistakes.
like other languages, can you have visual studio automatically underline with red color?


texts: How to make my character double jump in unity3d using CharacterController?

texts:
I can now control my character in air, I used Unity's CharacterController.Move docs, but now I need to make my character double jump.

Here's the code.

public class PlayerMovement : MonoBehaviour
{

    // Moving fields
    float speed = 6;
    float jumpSpeed = 8;
    float gravity = 20;
    Vector3 moveDirection = Vector3.zero;
    CharacterController controller;
    bool isJumping;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (controller.isGrounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump")) moveDirection.y = jumpSpeed;
        }
        else
        {
            moveDirection.x = Input.GetAxis("Horizontal") * speed;
            moveDirection.z = Input.GetAxis("Vertical") * speed;
        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}


texts: Assign a ScriptableObject to MonoScript through code

texts:
Sample code:

public class Item : MonoBehavior
{
    public ItemObject item; //the scriptable object

    void Start(){ // do stuff}

}

Normally I would drag and drop the asset of the ScriptableObject in the inspector.

How can I find and assign the asset (from Project View) through the script during runtime and possibly add it to a List<> or Array[]?


texts: Changing handedness coordinate system between unity and opencv

texts:
For my problem given System A, opencv and unity.
I have the

Inversed extrinsic parameters in the "System A convertion".
Intrinsic parameters (Can form into projectionMatrix) in the "Opencv convention".

My first question is
When I'm doing the projection. Do i need to convert a convention to have the same direction as opencv then I do the projection. Or I can do it directly without any negated axis?. The step you can see below.
===========================================================================

I want to set the camera from System A into the unity. What I did is following the image.

I rearrange the axis from System A to be the same as Unity. (Rotating + Negated the sign)

Once it had the same convention to the unity.I took the rotation matrix and use the scipy.transform.as_euler(R, order='zxy'). Then negated the sign the get the angle for left-handed.

Rotation into Euler angles by using scipy.transfrom.as_euler (order of 'zxy' following unity document). Since the scipy accept the right-handed coordinate system. Then i will got an angle of rotation. Then negated the axis.

Translation : I don't know that this should got negated the direction of an axis

My second question is
I think my procedure is wrong. Since the scipy libs accept the right-handed system. So I don't know that how to find the euler rotation angle from given rotation matrix in the right-handed system and change it into the left-handed system.
Thank you very much,
Regards,
Puntawat Ponglertnapakorn


texts: Unity 3D [C#] - How to properly reset a scene

texts:
I have a problem when I try to reset a scene. It doesn't seem to run, I have a script (of all scripts that have Awake and Start methods on that scene) that on the Awake method starts a coroutine, but when reseting the scene it doesn't even run it. I've read that it may be a problem of using the DontDestroyOnLoad method, but that doesn't seem to solve the problem since that script on the start takes a lot of references of objects that are only on the scene that I want to restart. I don't use any static variables on any script.

I made an unitary test trying to restart a scene with just one object and one script attached, on its Start method it also starts a coroutine but even in that test it doesn't even run the coroutine.

Here's the script of the unitary test:

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

public class LoadingSceneController : MonoBehaviour
{
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
    //Scene scene;
    // Use this for initialization
    void Start()
    {
        //scene = SceneManager.GetActiveScene();
        DontDestroyOnLoad(this.gameObject);
        useStartCoroutine();
    }

    void useStartCoroutine()
    {
        StartCoroutine(loadScene());
    }

    IEnumerator loadScene()
    {
        yield return new WaitForSeconds(3);
        SceneManager.LoadScene("gameplayScene 1");
        //SceneManager.LoadSceneAsync("gameplayScene 1");
    }
}


texts:
(Someone on gaming told me to better post this here.)

So in a lot of games lately I've seen this weird "light interference effect" where objects on the edges of my screen become red and blue blurry. My questions are:

What's this effect's name?
Why is it there?
Why do so many games use
it?

Here's a picture of what I mean:


texts: How to keep my Unity build from minimizing when I switch focus to an app on another monitor?

texts:
I have a multi-monitor setup. We are doing a lot of demos right now.  I have my meeting controls on one screen and my Unity build on another one that is shared.  When I click anything on any other monitor, the Unity build minimizes.  My build was initially set to "Fullscreen Window" but in an attempt to resolve this issue I have set it to "Maximized Window" but this did not fix the issue.

How can I interact with apps on another monitor without minimizing my game?


texts: Is storing data via property lists in an iPhone application's documents directory secure?

texts: Is storing game state in plists in an iPhone application’s documents directory a secure method?  Meaning, does anything other than the application have access to that directory?


texts: Performance of pixel shaders vs. SpriteBatch: XNA

texts:
Precondition: I read this question/answer about using shaders, or spritebatch, to render and mark a sprite.

I need to do something like that. I also have a 2D lighting PoC which I need to write. The way it will work will basically be something like:

Draw all the sprites
Draw lighting gradients to create a lighting texture
Multiply/add the lighting texture to achieve different effects

(I use multiple passes of add/multiply the lighting texture to achieve different effects.)

My question is really about a generalization: can I say with certainty that pixel shaders are always faster than adding/multiplying textures to the SpriteBatch? Or that adding/multiplying is always faster? Or if it's not generalizable, how do I decide which approach to take, given that I can probably code either of them?

(If it matters, I'm using MonoGame 3.0 beta for Windows games)


texts:
I want to make a game with UDK for mobile and I wonder if There is any limits?

I mean, for example, can I use UTPawn as my base Pawn class when making a game for my mobile(iOS) game?

How can I know which classes are legal in my case?


texts:
I want the best visual result on my Windows Phone if I scale down my sprites from 1920x1080 pixel resolution to 800x480 pixel resolution.

How can I use a filter to scale down my sprites? Which filter is the best?


texts: Error compiling irrlicht android using ndk in Mac

texts:
I'm new to irrlicht and I have started with irrlicht android port. I have made the following changes to android.mk file:

LOCAL_CFLAGS := -O3 -DANDROID_NDK -DDISABLE_IMPORTGL -I./../include/ -I./include/ -I/documents/karthik/android/android-ndk-r9/platforms/android-18/arch-arm/usr/include

LOCAL_LDLIBS := -L/documents/karthik/android/android-ndk-r9/platforms/android-14/arch-arm/usr/lib/libGLESv1_CM.so -ldl -llog -L/documents/karthik/android/android-ndk-r9/platforms/android-14/arch-arm/usr/lib/libGLESv1_CM.so

I have tried compiling irrlicht android using ndk-build in terminal.It showed the following errors at first:

In static member function 'static void irr::os::Printer::log(const c8*, irr::ELOG_LEVEL)':
error: format not a string literal and no format arguments [-Werror=format-security]
In static member function 'static void irr::os::Printer::log(wchar_t const*, irr::ELOG_LEVEL)':
 error: format not a string literal and no format arguments [-Werror=format-security]
In static member function 'static void irr::os::Printer::log(const c8*, const c8*, irr::ELOG_LEVEL)':
error: format not a string literal and no format arguments [-Werror=format-security]
In static member function 'static void irr::os::Printer::log(const c8*, const path&, irr::ELOG_LEVEL)':
error: format not a string literal and no format arguments [-Werror=format-security]
make: *** [obj/local/armeabi/objs/irrlicht/os.o] Error 1

and then I googled that and made changes in os.cpp file as follows:

Changed the code,

__android_log_print(ANDROID_LOG_INFO, "log", message);

to

__android_log_print(ANDROID_LOG_INFO, "log","%s", message);

This change solved that issue, and then I got another error:

In file included from jni/importgl.cpp:55:0:
jni/importgl.h:37:22: fatal error: GLES/egl.h: No such file or directory

Again I changed GLES/egl.h to EGL/egl.h and solved that issue, got:

fatal error: irrlicht.h: No such file or directory

I even solved this , atlast I'm here with this error:

error: 'EglDisplay' was not declared in this scope
error: 'EglSurface' was not declared in this scope
error: 'EglWindow' was not declared in this scope
error: 'EglContext' was not declared in this scope


texts:
So I have multiple gameobjects that needs to be interactable and I've put them all in one gameobject container. But the thing is I still have to attach the script into each of the gameobjects that needs to be interactable for it to work and that seems kinda iffy when a scenario comes that I have to add more gameObjects.
Is it possible to just put the script in the container object? I tried this on my container object and I'm pretty sure I'm doing something wrong.
public GameObject spriteHandler;
GameObject sprite1;
GameObject sprite2;
GameObject sprite3;
private void Start()
{
    sprite1 = spriteHandler.transform.GetChild(0).gameObject;
    sprite2 = spriteHandler.transform.GetChild(1).gameObject;
    sprite3 = spriteHandler.transform.GetChild(2).gameObject;
}
void OnMouseDown()
{
    Debug.Log("Clicked");

}


texts:
This is my swipe detection code. This code uses touch input. I want to do this using the left mouse button. So basically I want to 'swipe' using the mouse.How can I achieve that?

public float maxTime;
public float minSwipeDist;

float startTime;
float endTime;

Vector3 startPos;
Vector3 endPos;
float swipeDistance;
float swipeTime;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if(Input.touchCount > 0) {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Began)
        {
            startTime = Time.time;
            startPos = touch.position;
        }
        else if (touch.phase == TouchPhase.Ended)
        {
            endTime = Time.time;
            endPos = touch.position;

            swipeDistance = (endPos - startPos).magnitude;
            swipeTime = endTime - startTime;

            if(swipeTime < maxTime && swipeDistance>minSwipeDist)
            {
                SwipeFunc();
            }
        }
    }
}

void SwipeFunc()
{
    Vector2 distance = endPos - startPos;
    if(Mathf.Abs(distance.x) > Mathf.Abs(distance.y))
    {
        Debug.Log("Horizontal swipe");
    }
    else if (Mathf.Abs(distance.x) < Mathf.Abs(distance.y))
    {
        Debug.Log(" vertical  swipe");
    }
}
}


texts:
when the start game in the client [localserver], the bullet can't forward in the space just fixed in the Gun, here image about what I say:https://imgur.com/prWNxBx "image"

network manager
https://imgur.com/mfcBo61 "image"

player
 https://imgur.com/DuOIy67 "image"

bullet
https://imgur.com/cVq5HFU "image"

and this my script

    void Update()
   {
      if(!isLocalPlayer){
          return;
      }
      if (Input.GetKey(KeyCode.Mouse0))
      {
         CmdBulletFire();
      }
   }
  [Command]
  void CmdBulletFire()
  {
    // create the bullet prefab
    GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);

    //add velocity to bullet
    bullet.GetComponent<Rigidbody>().AddForce(transform.TransformDirection(Vector3.forward * 50000f));
    //Spawn the bullet
    NetworkServer.Spawn(bullet);
    //Destroy the bullet
    Destroy(bullet, 5f);
}


texts: Texture mapping issue in my Wavefront *.obj parser

texts:
I wrote a simple *.obj parser reading read vertices, texcoords and normals. But when I draw a model the texture isn't mapped correctly.

I have already tried uv.y = 1.0f - uv.y to get inverted Y axis coordinates as suggested by a few people but my textures are still displayed skewed.

I know that both texture file and rendering code are correct. Because when I render a plane and use hand written and hard coded texture coordinates and vertices it renders fine. I can render a textured cube by hand fine, too.

I use an index buffer to store vertex elements and I use the face elements provided by the *.obj file to fill texture coordinate buffer and normal buffer.

Model::Model(const string &givenName, const string &filePath){
    name = givenName;

    std::ifstream in(MODEL_PATH+filePath, std::ios::in);
    if(!in){
        error("Model \"" + filePath + "\" does not exist");
        return;
    }

    ModelMeshIndex tempindex;

    vector<vec3> normals;
    vector<vec2> uvs;

    string line;
    while(getline(in, line)){
        if(line.substr(0,2) == "v "){
                    std::istringstream s(line.substr(2));
                    vec3 v(0.0f);
                    s >> v.x >> v.y >> v.z;
                    data.vertices.push_back(v);
        }
        else if(line.substr(0,2) == "vt"){
                    std::istringstream s(line.substr(2));
                    vec2 v(0.0f);
                    s >> v.x >> v.y;
                    //v.y = 1.0f-v.y;
                    uvs.push_back(v);
        }
        else if(line.substr(0,2) == "vn"){
                    std::istringstream s(line.substr(2));
                    vec3 v(0.0f);
                    s >> v.x >> v.y >> v.z;
                    normals.push_back(v);
        }
        else if(line.substr(0,2) == "f "){
                    std::istringstream s(line.substr(1));
                    char tmp; // For the slashes between elements
                    unsigned short a,b,c, d,e,f, g,h,i;
                    s >> a >> tmp >> d >> tmp >>g;
                    s >> b >> tmp >> e >> tmp >>h;
                    s >> c >> tmp >> f >> tmp >>i;
                    a--; b--; c--; d--; e--; f--; g--; h--; i--;
                    data.index.vertexElements.push_back(a);
                    data.index.vertexElements.push_back(b);
                    data.index.vertexElements.push_back(c);

                    data.index.uvElements.push_back(d);
                    data.index.uvElements.push_back(e);
                    data.index.uvElements.push_back(f);

                    data.index.normalElements.push_back(g);
                data.index.normalElements.push_back(h);
                    data.index.normalElements.push_back(i);
        }
        else if(line[0] == '#') continue;
        else continue;
    }

    for(unsigned int i = 0; i < data.index.normalElements.size(); ++i)
        data.normals.push_back(normals[data.index.normalElements[i]]);

    for(unsigned int i = 0; i < data.index.uvElements.size(); ++i)
        data.uvs.push_back(uvs[data.index.uvElements[i]]);

    //data.uvs.push_back(vec2( 0.0f, 0.0f)); // bottom left
    //data.uvs.push_back(vec2( 0.0f, 1.0f)); // top left
    //data.uvs.push_back(vec2( 1.0f, 0.0f)); // bottom right
    //data.uvs.push_back(vec2( 1.0f, 1.0f)); // top right

    good = true;
}

What is wrong with my parser?


texts: Meaning of errors when compiling Source animated assets

texts:
This question will be composed of 3 somewhat separate questions regarding the creation of animated assets in Source. The documentation is quite poor and I am having a hard time understanding the errors that the model compiler throws.

1. Parent bones

I was trying to modify the collision mesh of an existing animated asset. I was able to make it work OK when animated in Blender but when compiled it throws something along the lines of "joint1 and joint2 have no parents, there can't be two root bones".

In the model viewer I can see two collision boxes, one static and another that is animated but which doesn't behave as I expected (it moves like the original collision mesh of the asset).

The problem disappears when I make all the vertices of the collision mesh have the same parent bone.
See https://developer.valvesoftware.com/wiki/Studiomdl_Data#Triangles
, it would be the  field (first column).

So the question is: does source allow you to have a collision mesh where all vertices don't share the same parent bone ? if not, how could I go around making a collision box that could be deformed (not only translated with the common parent bone) ?

2.  Conflicting bone names?

Sometimes, when creating certain skeletons the compiler throws the following error:

<Sergiy> Conflicting bone names: root vs root vs aaaa, try deleting one of the bones.
This is an old bug in studiomdl code that is about to be deprecated, so it may not be worthwhile fixing it

and the compilation is totally stopped. I tried renaming the bones, and changing the bones hierarchy to no avail. It should be noted that there are no two "root" named bones as the error might suggest. Even more, sometimes it shows three different named bones.

I don't understand what could be the cause of the error.

3. bone_followers

Finally, I noticed that the .qc of the decompiled model of some asset has a part like this:

$KeyValues
{
    bone_followers
    {
        "bone" "joint15"
    }
}

what does this (bone_followers) do?


texts: save generated gameobject to an array for shuffling

texts:
hey everyone i have this script here that breaks down a sprite into pieces and makes each one a gameobject.im having touble saving them into an array so i can shuffle them as gameobjects.
 public void Start()
    {

        GameObject spritesRoot = GameObject.Find("SpritesRoot");
        Debug.Log("Array length: " + array2D.GetLength(0));

        for (int i = 0; i < array2D.GetLength(0); i++)
        {
            Debug.Log("x: " + array2D[i, 0]);
            Sprite newSprite = Sprite.Create(source, new Rect(array2D[i, 0], array2D[i, 1], array2D[i, 2], array2D[i, 3]), new Vector2(0.5f, 0.5f));
            GameObject n = new GameObject();
            SpriteRenderer sr = n.AddComponent<SpriteRenderer>();
            sr.sprite = newSprite;
            n.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(array2D[i, 0], array2D[i, 1],0),0);
            n.transform.parent = spritesRoot.transform;
        }

    }

my shuffle function is this
 public void Shuffle(GameObject[] gameObjects)
    {
        for (int i = 0; i < gameObjects.Length; i++)
        {

            // Find a random index
            int destIndex = Random.Range(0, gameObjects.Length);
            GameObject source = gameObjects[i];
            GameObject dest = gameObjects[destIndex];

            // If is not identical
            if (source != dest)
            {

                // Swap the position
                source.transform.position = dest.transform.position;

                // Swap the array item
                gameObjects[i] = gameObjects[destIndex];
            }
        }
    }
```


texts: Do we have to worry about byte orders in the process of programming a game? Do game consoles use different byte orders?


texts: Unity, Object's vectors are not rotating with the object. what did i do wrong?

texts:
I found a youtube video (Sebastian Lague: Character Creation (E07: Unity character controller)) that has a really good movement script, I understood it and used it for my character.

When I started moving it, I noticed that the character rotates but his blue, red, green vectors are not rotating with him, his forward always stays the same, whereas in the youtube video his vectors rotated with the object, what could i have done wrong here?

 Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    Vector2 inputDir = input.normalized;

    //if (inputDir==new Vector2 (0,1))
    //    transform.eulerAngles = new Vector3(0, Camera.main.transform.eulerAngles.y, 0);
    //Debug.Log(Input.GetAxis("Mouse X"));

    if (inputDir != Vector2.zero)
    {

        float TargetRot = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg;
        transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, TargetRot, ref TurnSmoothVelocity, TurnSmoothTime);

    }

    bool running = Input.GetKey(KeyCode.LeftShift);
    float TargetSpeed;
    if (running == true) TargetSpeed = RunSpeed * inputDir.magnitude;
    else TargetSpeed = WalkSpeed * inputDir.magnitude;
    CurrentSpeed = Mathf.SmoothDamp(CurrentSpeed, TargetSpeed, ref SpeedSmoothVelocity, SpeedSmoothTime);

    transform.Translate(transform.forward * CurrentSpeed * Time.deltaTime, Space.World);

}


texts: Architecture of "doodle jump" type gameplay infinite looping background

texts:
I am planning make a doodle jump type game, character jumping on platforms. A scrolling or doodle jump like background which ll appear to move when character moves upward and appear moving (just like in doodle jump) so, my thoughts are for this kind of background is

to take a large image i.e of 2048x2048, make 2 planes, set this texture to them, when first image ends other ll move its position on top of first, when second ends first ll move on top of second and so on.
Other approch could be a "Instantiate" and "Destroy" of small images having textures on them according to jumping character position ( which i doubt ll b expensive )

They are my thoughts, I want to go for best approach and would like to listen the best one. Is there any more appropriae way to achieve moveable background, I ll appreciate your suggestions. Thanks.


texts: Various versions of DirectX are available on both Windows and Xbox. Are the libraries the same on both platforms? Obviosly I'm talking about the interfaces — such as the ones for working with windows, input, etc —, not their actual implementation.


texts: How to get the attack animation cycle all the way through after one KeyEvent without twitching? (Java awt)

texts:
So I figured by myself (supposedly) how to make the attack animation cycle all the way through after pressing a key without needing to keep it pressed. But now it doesn't always start at the same frame index and sometimes doesn´t even complete the animation (as you will see, sometimes it does). Heres a gif of what's going on.

These go in the constructor

    aR = new Animation(50, Assets.aRight);
    aL = new Animation(50, Assets.aLeft);
    aF = new Animation(50, Assets.aFront);
    aB = new Animation(50, Assets.aBack);

I use this timer to keep track of the cooldown and also set the flag (timerFlag) that indicates the start of the attack animation to true.

    attackTimer += System.currentTimeMillis() - lastAttackTimer;
    lastAttackTimer = System.currentTimeMillis();
    if(attackTimer < attackCooldown){
        timerFlag = false;
        return;
    }

    if(!handler.getKeyManager().attack)
        return;

    timerFlag = true;

(after a little bit of code attackTimer is set to 0)

To decide what the game will render I use an int (stillLock) that saves the last direction the player faced and I have a second static flag that indicates that the animation started. (I even reset the index every time it starts just to make sure *sadface)

else if(timerFlag&&!animCd){

        switch (stillLock){
        case 1:      //to attack
            animCd = true;
            timerFlag = false;
            aL.setIndex(0);
            return aL.getCurrentFrame();
        case 2:
            animCd = true;
            timerFlag = false;
            aR.setIndex(0);
            return aR.getCurrentFrame();
        case 3:
            animCd = true;
            timerFlag = false;
            aB.setIndex(0);
            return aB.getCurrentFrame();
        case 4:
            animCd = true;
            timerFlag = false;
            aF.setIndex(0);
            return aF.getCurrentFrame();
        }
    }
    else if(animCd){
        switch (stillLock){
        case 1:         //to finish attack animation
            aL.tick();
            return aL.getCurrentFrame();
        case 2:
            aR.tick();
            return aR.getCurrentFrame();
        case 3:
            aB.tick();
            return aB.getCurrentFrame();
        case 4:
            aF.tick();
            return aF.getCurrentFrame();
        }

And this is the Animation class where the magic happens

public class Animation {

private int speed, index;
private long lastTime, timer;
private BufferedImage[] frames;

public Animation(int speed, BufferedImage[] frames){
    this.speed = speed;
    this.frames = frames;
    index = 0;
    lastTime = System.currentTimeMillis();
    timer = 0;
}

public void tick(){
    timer += System.currentTimeMillis() - lastTime;
    lastTime = System.currentTimeMillis();

    if(timer > speed){
        index++;
        timer = 0;
        if(index >= frames.length){
                index = 0;
                Player.animCd = false;
        }
    }
}

public BufferedImage getCurrentFrame(){
    return frames[index];
}

public void setSpeed(int speed){
    this.speed = speed;
}

public void setIndex(int index){
    this.index = index;
}

}

And finally it renders like this.

public void render(Graphics g)
{
    g.drawImage(getCurrentAnimationFrame(), (int) (x - handler.getGameCamera().getxOffset()),
            (int) (y - handler.getGameCamera().getyOffset()), width, height, null);
}

I'm trully sorry for the code dump, I swear I worked hard narrowing it down only to the important stuff and being specific. Hope you can help me, I've been stuck with this for weeks... :)


texts: How can I convert an html5 web game to an android app?

texts:
I have already made an html5 game and it is in service.
I want to service this at Android app too.
I know little about Java or Kotlin, so I think the least risky way is to use a webview.
There is already a function to save game data with Oauth authentication.
I thought this part should be replaced with google play Oauth.

However, there is a problem that the app does not run when the player is offline. (Run the app fails to load any html document)

However, if you load a local html file, it will be rejected from the existing firebase SDK because there is no domain.

In fact, I know very little about native app development, so I don't know that what I don't know, what I need.

What should I do in this situation?

Do I need to rebuild my app in Kotlin or Java from scratch?
Do I have to use the same engine as Unity?
Do I have to rebuild with a framework like cordova?

The question may not fit here, but I need help. Please.


texts: pathfinding with obstacles in a Warcraft 3 like game

texts:
Consider A* searching on a tile based map. A straight forward code would be: If there is an unit inside that cell, then it is unreachable, this is ok.

But there is map resolution issue. When I look into Warcraft 3, there monsters and structures does have different radius, and you can walk very close, which is more like vector based, how this was implemented?

Also, what is the standard solution to incorporate moving obstacles collision detection with path finding algorithm, like Warcraft 3?


texts: Checking if a vector is contained inside a viewing frustum

texts:
I have a three dimensional pyramid given by four vectors a, b, c, d and want to test if a given vector x is inside that region or not. Here is an image:

A related question can be found here: 2D problem.

How can I test to see if the vector is contained by the others?


texts: I was designing games in unity with some friends but none of us have a mac so none of us can download the apple sdk.  To use the sdk, we will have to run a virtual machine with osx on it.  Virtualization is disabled on most PCs by default and I was wondering if there was any way to change that without rebooting into the bios.  If not, how would I change it in the bios?  Thanks for your help.


texts: How can I design an effective game object interaction scheme with a component-based architecture?

texts:
This is a design question... I'm sure this could be generalized more, but I'm having a hard time with it. I am wondering about design for game object interactions - here is my example (2D puzzle-platformer).

Say the player is trying to progress through a level. There are many lights that can be pointed in different directions. Here is an example of how these light objects might interact...

One light projects a platform that allows the player to cross a gap
One light decreases the friction coefficients of anything it touches, another increases it
One light nulls the effects of all lights, which would make the platform disappear while that light is on and null the friction modifiers
Etc...

What is the best way to approach this problem when using a component architecture? Components for each major object seem obvious, as well as a clean way to define their effects on the environment. A class to "resolve" interaction (seems like that could become a mess quickly)? Some usage of the decorator pattern to create combined objects for those that are interacting at a given time? A data structure that lends itself to this?

Also, connecting audio to these interactions? It seems like connecting audio to the system would be just like connecting any other property, like visibility or player movement/collision.

Obviously as more components are added it would be nice if there was a robust system that could handle new ones with little modification, but I am not familiar with how to go about designing this.

Other Information:
The engine I am using is an XNA engine called IceCream.


texts: What is the difference between OpenGL 1.x and 2.x?

texts:
Is there a good tutorial that shows the difference between OpenGL 1.* and 2.*?

It would be very helpful to know which functions I should not be calling (like glBegin(), I assume).


texts: networking - how to deal with serverside packet arrival delay?

texts:
Let's assume each client sends a packet every 0.05 seconds. (rate = 20)
Server update tickrate is 60 and it sends data back to client every 1 / 30 seconds.
Now client A has 50ms ping time and it sent each data at [A]5, [B]5.05, [C]5.10 second.
But due to some networking issue, server received each data at [A]5.05(good), [B]5.10(good), [C]5.18(bad! it delayed 0.03 seconds.)
When server get the packet [A] at 5.05 seconds, since each packet contains client data(like commands) for 0.05 seconds, it updates the entity based on this [A] packet for 0.05 seconds. after that, server time is now 5.10. and the next packet, [B] is already arrived so server just can keep updating.
At 5.15, now server has to update the entity with next packet, which is C, but there's no packet! Server has to wait for 0.03 seconds till next packet will be arrived. now, server is behind 0.03 seconds from client. sync failed.

I have two idea for solving this problem.

Server maintains its own client's time and sends back to client. For client side, when there is heavy desync between client and server, the client syncs to the server time.

Solution 1 is still applied. but there is one more. like entity-interpolation, there is packet-interpolation. Client sends each packets every t seconds which is (t = [SEND-TICKRATE + CLIENT-LAG]) . It means server gets next packet after [t + LATENCY] seconds which is always larger than SEND-TICKRATE, 0.05 in this assumption.
So when server gets packet, it doesn't update it immediately but waits for some time (like 0.03 ~ 0.05 seconds). Now server has next packet with a high probability.

I think Solution 2 is good. But the drawback is, client renders other player's data behind [RTT + Entity-Interpolation time + Server packet Interpolation time], so for a fast-paced-game, Shot-behind-the-wall will more happen.
What technique is used in other fast-pace-game like league of legends or overwatch?


texts:
I have 2 lists of coordinates in C# one as of coordinates of Drivers and the other as of coordinates of cafes. I am looking for an efficient way of populating a static Dictionary with its key as of a Driver from the first list and its associated values of all Cafes in 500 meters radius. Number of cafes can be up to 100000 and number of Drivers are dynamic from 1 to 100000

public void ManageList() {
GlobalList.Clear();
foreach (var driver in driverList)
    {
        var driverCoords = new GeoCoordinate(driver.Latitude, driver.Longitude);
        List<Cafe> matchedCafes = new List<Cafe>();

        foreach (var cafe in cafeList)
        {
            var cafeCoords = new GeoCoordinate(cafe.Latitude, cafe.Longitude);

            if (cafeCoords.GetDistanceTo(driverCoords) <= 500) {
                matchedCafes.Add(cafeCoords);
            }
        }

        GlobalList.Add(driverCoords, matchedCafes);
    }
}

the above works fine as long as drivers are not movable objects. If I want to send the driver's coordinates every 5 seconds and update the GlobalList per driver the above algorithm fails as I am basically clearing the whole list and populate it again.


texts: How fast do games in Flash C++ Compiler execute compared to C++?

texts:
Flash Player can now run C++ code, that is cross complied with the Adobe Flash C++ Compiler. How fast does such code run in comparison to a C++ application running as an EXE, in the context of gaming?

And does GPU rendering performance compare with C++ applications? Or is Flash far behind?


texts:
I am trying to implement Dual Contouring, following serveral sources, mainly http://www.sandboxie.com/misc/isosurf/isosurfaces.html
but now I want to implement finding the feature point as explained in this post https://gamedev.stackexchange.com/a/83757/49583

It begins with

  The QEF you are minimizing is simply the total distance to each of the planes that are defined by the intersection point/normal pairs for that cell.

I do have the intersection point, which is just the edge vertices averaged by their densities.
I got the normal by averaging the normal of the edge vertices.
I do it like this :

        //calculate normals by gradient of surface, d(x,y,z) = density function, d0 = density at p0, d1 = density at p1
        Vector3 n0 = new Vector3(d((int)(p0.x+1),   (int)p0.y,      (int)p0.z       ).Value - d0,
                                 d((int)p0.x,       (int)(p0.y+1),  (int)p0.z       ).Value - d0,
                                 d((int)p0.x,       (int)p0.y,      (int)(p0.z+1)   ).Value - d0);
        Vector3 n1 = new Vector3(d((int)(p1.x+1),   (int)p1.y,      (int)p1.z       ).Value - d1,
                                 d((int)p1.x,       (int)(p1.y+1),  (int)p1.z       ).Value - d1,
                                 d((int)p1.x,       (int)p1.y,      (int)(p1.z+1)   ).Value - d1);

        this.normal = Vector3.Lerp(n0,n1,m);

My plane is this :

Vector4 plane = new Vector4(edge.normal.x, edge.normal.y, edge.normal.z, Vector3.Dot(edge.point, edge.normal));

And I have a vertex at (x,y,z),

  Basically, you start the vertex in the centre of the cell. Then you average all the vectors taken from the vertex to each plane and move the vertex along that resultant...

How do I get the vector from the plane to the vertex?


texts:
I have a problem with my first test on Unity, it's a simple motorcycle game. I found a script to start learning and runs very good, is this (answers.unity3d.com/questions/528298/bike-physics.html).
Well, the bike is moving good, and turns well, the problem comes when I try to knock down the bike. I'm using this example (docs.unity3d.com/ScriptReference/Transform-rotation.html), and the movement is perfect, but the bike don't turns as expected, making a strange movement (a small jumps, seems a bug xD).
What is the correct (and easy) way to get work the wheels on bike, because on car works perfectly.
Sorry for my english, and I appreciate a answers for noobs to my question, please.

I'm thinking on the possibility of keep the wheelcolliders always straight and rotate the other parts of the bike...
Or here, the user reccomends a sphere collider...but, how to make a "wheelcollider" with a spherecollider??
I'm very lost...

A lot of thanks!!!

----- EDIT -----

PROBLEM SOLVED!!
This is the code I used to solve the problem, I don't know if is correct but works perfect for me:

//INCLINACION MOTO AL GIRAR
var tiltAroundZ = -(Input.GetAxis("Horizontal") * tiltAngle);
var target : Vector3;
target = Vector3 (0,0,tiltAroundZ);
var deltaRotation : Quaternion = Quaternion.Euler(target * Time.deltaTime);
// Dampen towards the target rotation
rb.MoveRotation(rb.rotation * deltaRotation);
if(Input.GetButton("Horizontal")==false)
{
if(rb.rotation.z > 0){
target.Set(0,0,-30);
deltaRotation = Quaternion.Euler(target * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);
}
if(rb.rotation.z < 0){
target.Set(0,0,30);
deltaRotation = Quaternion.Euler(target * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);
}


texts:
This may be hard to understand because this is hard to explain

I have 6 scenes and one 'start' scene.

The start scene will be where my scene manager is.

So I want function where when the player clicks on the the start scene it goes to a random scene (from the 6 scenes) and then it goes to start. Then when you click again it goes to random scene, but this time these random scenes will be between the remaining 5 (excluding the scene the player just went on) and then it goes back to start. Then it goes to a random scene time, this time these random scene will be between the remaining 4. And so one.

I already know how to go a random scene and back but I don't know how to do the remaining


texts: I want to add slow motion effect with a collision as a trigger. So I want to have an effective way to trigger a slowmotion effect on bodies as well as sprites that can be caled in the update method. Can anyone please help me with this or provide a link as to where I can find the answer?


texts: How to access the players XBOX account from your Windows 10 game app?

texts:
We want to release a game that was previously an Android game for Windows 10 (Store / Desktop). Could you tell me how we can access the players XBOX account, see his friends and compare their scores? We also want to display their profile pictures. Sadly we don't even have an idea how the API we're looking for is called. We're confused by these "universal app" things. I saw something similar in the Minecraft app for Windows 10. Our Engine is the latest version of Unity, by the way. If informations are missing, please let me know.

All I have to know is where to find the API and it's name. A link to tutorials could be useful :)

Thanks!


texts: Java Thread.sleep() VS Get last and current time

texts:
I am creating a simple game using Java. I'm not using any game library. I just want to know if it is okay to call Thread.sleep(40) before calling repaint().

public void run() {
    while(isGameRunning) {
        try {
            Thread.sleep(40);
            repaint();
        }
        catch(Exception e) {
        }
    }
}

or should I use:

private long last_time = System.nanoTime();
private double ns = 1000000000/25D;
private double delta = 0;
@Override
public void run() {
    while(Universe.IsGameRunning) {
        long time  = System.nanoTime();
        delta += (int)(time - last_time)/ns;
        last_time = time;
        System.out.println(delta);
        if(delta>=1) {
            repaint();
            delta--;
        }
    }
}

The code below has more CPU and RAM usage than the first one. Can you explain to me how 'Delta Timing' actually works?


texts: Realistic angular velocity for rolling sphere in Unity 5.1

texts:
I'm trying to make a small 2D game with a rolling ball/sphere using Unity 5.1, but if find the angular velocity of the ball weird.

On this first image (http://imgur.com/8wBoGms), you can see the sphere in 2D and in its initial position. On this second image (http://imgur.com/ArCRSZn), the sphere was moved by rolling until it made a 90° turn.

But the distance traveled by the sphere is greater than it should, if you wanted to be to be realistic :
you can see that the radius of the circle is equal to the size of the squares' sides, so the circle circumference should be equal to ~6.28 (in square side size). If the sphere was traveling realistically, it should travel ~1.57 (in square side size) to turn 90°.
But in the second image, we can see that it take 3 and not 1.57 .

The controller of the sphere is simply adding a force when a left or right button is pressed :

public class PlayerController : MonoBehaviour
{
    public float speed;
    private Rigidbody2D rg2d;

    void Start()
    {
        rg2d = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxisRaw("Horizontal");

        Vector2 movement = new Vector2(moveHorizontal, 0.0f);
        rg2d.AddForce(movement * speed * Time.deltaTime);
    }
}

So my question is : how can I make the angular velocity realistic in this situation? Or am I doing something wrong?

Thanks for taking the time, I really appreciate !


texts: How can I maneuver an AI pirate ship for a sea battle?

texts:
I'm trying to picture in my head what would be required to make an AI controlled enemy do the following in a top down pirate sailing game:

Approach the player ship
Bring player in line with port / starboard guns
Keep guns trained on player
Be able to manoeuvre around obstacles
Not cheat acceleration to achieve the above

When I first started thinking about the idea it was quite simple, but the more I think about it, the more complex the requirements become; with the major problem being the AI calculating perfectly the curve required to come up along side the player, or to better yet, make a pass along their bow / stern before coming along side without needing to let them quickly speed up / slow down to achieve this.


texts:
Here's my dilemma : I want to have light sources placeable by the player, in terms of lanterns.

I know the best way to do this is to use pixel shaders, which I have done a lot of research and use on, but it seems so far that the lights are static.

So what would be the best method to create a dynamically lit scene?

I already have to workings of a few classes to make 2d lights (Color, Position, Type, Direction, Power) but it is just rendering that is the problem.

Thanks for your considerations!


texts:
I have a hexagonal grid of fields, each field has a certain terrain type. I assign every vertex of hexagon with terrain type and pass it as attribute to vertex and then fragment shader. Then I use the extrapolated value to blend terrain textures together.

For instance: 1 is grassy, 2 is desert.

Vertex shader:

varying vec2 vUv;
attribute float terrainType;
varying float vTerrainType;

void main()
{
   vUv = uv;
   vTerrainType = terrainType;
   vec4 mvPosition;
   mvPosition = modelViewMatrix * vec4( position, 1.0 );
   gl_Position = projectionMatrix * mvPosition;
}

Fragment shader:

uniform vec3 diffuse;
uniform float opacity;
varying vec2 vUv;
varying float vTerrainType;
uniform sampler2D map;
uniform sampler2D map1;

void main()
{
   gl_FragColor = vec4( diffuse, opacity );
   vec4 texelColor = texture2D( map, vUv ) * (2.0 - vTerrainType) + texture2D( map1, vUv ) * (vTerrainType - 1.0);
   gl_FragColor = gl_FragColor * texelColor;
}

Implementation is WebGL, if it makes any difference.

The result looks really unnatural, so is there any way to make it smoother and rounder?


texts:
I've been studying steering and flocking behaviors, if not directly from Craig Reynolds work on Steering Behaviors For Autonomous Characters (http://www.red3d.com/cwr/steer/). I understand the basic concepts and how to apply forces but the main issue with this is performance. Using Unity, ECS and the job system, I have been able to implement a multi-threaded implementation of some simple behaviors (seek, arrival, evade etc).

The problem is simply that all of the implementations of steering behaviors that I find are all based on this same principle and they all seem to suffer from the same problem - framerate independence. For example, a simplified example of seeking:

// get a vector pointing directly at our target, at the maximum speed.
desired_velocity = normalize(target - position) * max_velocity

// get the steering force direction
steering = desired_velocity - velocity

// ensure the steering force never exceeds our maximum steering force
steering = truncate(steering, max_steering_force)

// ensure the velocity never exceeds the max speed
velocity = truncate (velocity + steering , max_speed)

// apply our velocity
position += velocity * delta_time

When dealing with the final velocity, we are utilizing delta_time to ensure that the velocity is applied in a framerate independent manner. But the steering force is not framerate independent at all. If this was running at 120fps, the steering would reach it's maximum velocity much faster than if the game was running at 30fps.

Is there something more I should be doing here. I've experimented with using delta_time with the steering, but that seems to make little difference.


texts: Can not connect HTC Vive headset - Steam VR plugin error Failed to load IVRRenderModels

texts:
When I add SteamVR plugin I receive error
Failed to load IVRRenderModels interface version IVRRenderModels_005.
The plugin works for my other projects, camera and controllers are detected and work fine.


texts: Architechture problem of implementation of a tutorial for a game

texts:
I'm creating one for my game and I'm confused a bit. I made special TutorialManager class and a number of steps to pass for player first time entered the game.

The problem is that tutorial steps are N separated classes, and each has some logic to lead the player. The problem is that I had to open (make public) a lot of private methods of UI and field to give TutorialStep classes ability to operate with objects I need, and it's an awful solution as far as I can see. But I have no idea how to organize it in other way.

I'm not sure I've described the problem clear enough, so any questions will be answered.


texts:
I'm planning to create a game on my own and will most likely hire an artist in the future. I just want to know if making a game in 2d will a lot cheaper than making it on 3d?

Here's my plan:

If it will be a 2d game.. I'll probably make a platform game. More like a Braid level of graphics.

If it will be a 3d game.. Closest of graphics I'll ask for will be far cry 1 or if possible oblivion.

So any thoughts? I'm funding all of it on my own. It will be my first game but will use maybe an engine around if it will be a 3d game. If 2d, I have my own engine lying around here.

Thank you, Balls


texts:
I'm working on a top down shooter in pygame and am having trouble getting bullets to fire. I'm using a class for the bullets, I'll show what I think is the relevant code.

This is what I do after the mouse button is clicked:

if event.type == pygame.MOUSEBUTTONDOWN:
        bullet_vel=[0,0]
        fired_pos=pygame.mouse.get_pos()
        player.fired=True
        bullet_pos_from_player=[0,0]

        bullet_pos_from_player[0]=fired_pos[0]-player.rect[0]
        bullet_pos_from_player[1]=fired_pos[1]-player.rect[1]
        bulletdistance=math.sqrt(abs((bullet_pos_from_player[0])^2) + abs((bullet_pos_from_player[1])^2))
        bullet_vel[0]=bullet_pos_from_player[0]/bulletdistance
        bullet_vel[1]=bullet_pos_from_player[1]/bulletdistance

        print bullet_vel[0], bullet_vel[1]

        bulletgroup.add(bullet((bullet_vel)))

and here is my class for the bullet:

class bullet(pygame.sprite.Sprite):
def __init__(self, bullet_vel):
    super(bullet,self).__init__()
    self.pos=player.draw_pos
    self.image=pygame.transform.rotate(bullet_image, player.angle)
    self.vel=bullet_vel

def update(self):
    self.pos[0]=self.pos[0]+self.vel[0]
    self.pos[1]=self.pos[1]+self.vel[1]
    screen.blit(self.image, self.pos)

Hope someone can help out,

thanks guys.


texts: Keeping a UI element inside the screen at all times

texts:
I have this UI element that follows an arrow around the screen. The problem is that sometimes, due to the parenting, the element goes outside the screen. I need a way for it to "hit the walls of the screen" and don't move beyond that point. This is made trickier by the fact that the UI element is animated, and "pops out" onto the screen.

I've tried several solutions and the best so far has only made it so that the pivot point does not go beyond the screen edge. I know I somehow have to  calculate a bounding rect for the UI element, and then Clamp() its edges in screen space, but I honestly have no idea how to do this in code.


texts:
I've been looking for a formula to plot (world->screen) and mouse pick (world->screen) isometric tiles in a diamond-shaped world.
The ones I've tried always seem to be, well, off.
What's the usual/correct way to do this?


texts: Dynamic entities using classes and objects

texts:
I'm trying to create a program which involves the creation of several characters/entities.

At the moment I have a Base Entity class an Entities class and a Main class. I can handle one entity alright, however I am trying to create each one editable through a standard function call.

Main Class: http://pastebin.com/AjgEBSke
Entity Class: http://pastebin.com/5y2wD3Qc
BaseEntity Class: http://pastebin.com/VfqRgeng

I feel a little confused on how to dynamically call and edit each specific character without limiting myself to lots of 'if' statements. I have tried to restart this project several times...

Basically I'm creating a private object in a class. That class will be used to talk to that private object, Save, load and edit etc.

Then in a seperate Entities class I create an instance of that object, this is where I think im getting caught up. As far as I know, I need to handle everything I want to do in that entity in this entity class.

I give the entity/object an ID, and a default name which I want to be able edit later. I also want to eventually be able to call that entity from other classes to 'draw' it, have it return the values I need to draw it, Name, body type etc (other variables in the object).

I have managed to interact with a specific instance of the object class by checking if the String is equal to an objects ID and then doing something, this however I feel is not dynamic and I'll just get into a bigger mess.

Ideally I think I want to be able to enter the object's class' instance name as a string and have it handle everything.

Sorry this has been rather long, if you know of any articles or information on how I'd learn to create dynamic entities to do what I need to do, that'd be great.

Im probably looking more for an explanation of the concept of what I'm trying to do as i've only just really sketched up this code. So this code might be a little pointless at the momemnt. Ive attempted it a few times, trying to set things up better each time, however ultimately fail when I try to make things behave dynamically. If i'm going about this completely the wrong way then please tell me as I'm still learning and don't want to get into the habit of doing things badly.


texts: FLIXEL: hexagonal tiles not seamlessly tiling with each other

texts:
I'm making a hex grid for our project using as3. I wonder why my hex grid isn't tiling properly.

Running my code within Flash CS6 produces seamless tiling

but on FlashDevelop it looks like this

Here is my code (in FlashDevelop):

    public class PlayState extends FlxState {
    private var player:PlayerSprite;
    private var hexMap:GenerateGrid;

    protected var hexagonWidth:int = 128;
    protected var hexagonHeight:int = 132;
    protected var hexagonNumber:Number = 0;
    protected var gridX_Size:int = 7;
    protected var gridY_Size:int = 10;

    public function PlayState() {

    }

    override public function create():void {
        FlxG.mouse.show();

        for (var yPos:int = 0; yPos < gridY_Size; yPos++) {
            for (var xPos:int = 0; xPos < gridX_Size; xPos++) {
                var hexagonX_Pos:Number = hexagonHeight * xPos + (yPos % 2) * hexagonWidth / 2;
                var hexagonY_Pos:Number = hexagonHeight * yPos / 4 * 3;
                hexagonNumber = xPos + yPos * gridX_Size;
                hexMap = new GenerateGrid(hexagonX_Pos - hexagonWidth, hexagonY_Pos - hexagonHeight);
                this.add(hexMap);
            }
        }

And for the class where the hex tiles are drawn

    public class GenerateGrid extends FlxSprite {
    [Embed(source = "../res/hextile_grass.png")] private var HexGrassPng:Class;

    public function GenerateGrid(X:Number = 0, Y:Number = 0):void {
        super(X, Y);

        var hex:FlxSprite = new FlxSprite();
        hex = loadGraphic(HexGrassPng, false, false);
        hex.x = X;
        hex.y = Y;
    }

    override public function update():void {
        //super.update();
    }
}

Any help would be greatly appreciated.

EDIT :
EDIT: I have noticed my mistake a while ago. Code should be var hexagonX_Pos:Number = hexagonWidth * xPos + (yPos % 2) * hexagonWidth / 2;


texts: Unity ball not bouncing off wall correctly

texts:
I have been making a brick breaker game in Unity in 2D as my first game. I have got the ball bouncing off the paddle correctly and can bounce it of the paddle at different angles. However, when the ball hits a wall or the roof it always bounces so its either traveling exactly in the X-directon or Y-direction regardless of what angle it hits the wall with instead of bouncing off at 90'.

Im not using any scripts to control the bouncing off the walls or roof just using  2D box colliders on the roof and walls (which are cubes) and a circle collider and 2D rigidbody on the ball (sphere) which Ive given a bouncy material.

Any help would be really appreciated.

Here's a gif of the problem: http://imgur.com/a/YJyNH


texts: How to fix pink tiles when there is a problem with the Shader?

texts:
Because of some dumb mistake I did fifth time, I had to repaint my level in my 2D game.
The problem is that the tiles I use from the Tile Palette turn into pink because of some shader error. I came to this conclusion after a long time of browsing through the forums.

I am 100% sure that this will happen again, because I don't know what causes this behavior. So, prevention is not an option for me.
What is the solution?

By @DMGregory's suggestion, I was able to recreate this dumb behavior of mine in an empty project.
What I do is dragging and dropping a tileset onto a tile palette which I am using, and then overwriting the current tile palette. Then, the former assets are lost (I guess?) leaving me with pink tiles.

Attached picture is one of my levels created using Tile Palette. How do I take this back? I don't want to repaint my level everytime I do whatever that causes this behavior.


texts:
I have imported the advertisement package from the package manager, turned the ads service on, and added a script:
string gameId = "correctGameId";
bool testAds = true;
void Start(){
    Advertisement.Initialize(gameId, testAds);
}

void Click (){
    if(Advertisement.isInitialised){
          Advertisement.Show();
    }
}

This Click function is called from a button's OnClick event.
Every time I play in the editor and click the button, nothing happens.
How can I make my advertisement show?


texts: how to get if a rotation/position has been completed?

texts:
I've done an if / else with the final position / rotation plus they never complete, how can I check this?
stays like this

https://i.imgur.com/3cQ9AEk.gif

    if(head == false)
        cam.transform.position = Vector3.Lerp(cam.transform.position, PosicMin, Time.deltaTime * Speed);
    else {
        cam.transform.position = Vector3.Lerp(cam.transform.position, PosicMax, Time.deltaTime * Speed);
    }
    if(head == false)
        cam.transform.eulerAngles = Vector3.Lerp(cam.transform.rotation.eulerAngles, RotationMin, Time.deltaTime*Speed);
    else {
        cam.transform.eulerAngles = Vector3.Lerp(cam.transform.rotation.eulerAngles, RotationMax, Time.deltaTime*Speed);
    }


texts: Physics-based dynamic audio generation in games

texts: I wonder if it is possible to generate audio dynamically without any (!) audio assets, using pure mathematics/physics and some input values like material properties and spatial distribution of content in scene space. What I have in mind is something like a scene, with concrete floor, wooden table and glass on it. Now let's assume force pushes the glass towards the edge of table and then the glass falls onto the floor and shatters. The near-realistic glass destruction itself would be possible using voxels and good physics engine, but what about the sound the glass makes while shattering? I believe there is a way to generate that sound, because physics of sound is fairly known these days, but how computationaly costy that would be? Consumer hardware or supercomputers? Do any of you know some good resources/videos of such an experiment?


texts: How to make Unity ground mix up with sky

texts:
I'm building up a scene with Unity, I want the plane to extend far enough and mixed up with sky like the picture showing bellow

The only way I can think off in unity is by creating two plane with 90 degree with each other to simulate this scene, I tried to set solid color for the sky but still there is clear gap between the ground plane and the sky, how do you manage to extend the ground far enough and mixed up with sky?


texts: Importance of scripting engine at Cocos2d Game Engine

texts:
Each Game Engine is different and solves different problems in different ways, so the engine design does vary greatly from engine to engine (even though a lot of principles are shared from engine to engine).

Cocos2D is a great product on it’s own, but it doesn’t expose engine functionality to a scripting Language like Lua, JavaScript etc.

My Question: How much important to integrate a Scripting Engine at Cocos2d?


texts:
I have a 2-d game that I am making, using 3-d assets, including TextMeshes for text. I have decided that in some instances, I would like to have the TextMesh appear behind objects in the foreground. The below is one such example.

It seems that the TextMesh is always in front. I have tried a number of things to get the text between the map and object layers, with no success. These include:

Moving the text between the map and object.
Changing the SortingLayers and SortingOrder. The map, objects, and labels are on 3 different layers, with the Objects being the highest layer, the map the lowest, and default and label in between.
Using a perspective camera, not orthographic.

Any ideas as to what else could be going on? Thanks!
How can I make the TextMesh appear that isn't on the top layer? Thanks!


texts: p2.js body position is NaN when spawned inside of each other

texts:
I'm working on a project for which I need a physics engine. At the moment I'm playing around with p2.js but I'm running into a problem:

When I try to create multiple bodies (circles and/or boxes) which overlap the positions are set to NaN as soon as world.step() is called. The bodies have a mass of 5 and are dynamic.

In very rare occasions it does actually work. How can I make sure it works every time? Do I have to wait for the bodies to be initialized?

4 circles before the simulation starts, once world.step is called the positions of these circles is NaN:

var world = new p2.World({
    gravity: [0, 9.82]
});
function PhysicsBody(type, x, y, widthOrRadius, height) {
    this.body = new p2.Body({
        mass: 5,
        position: [x, y],
    });
    this.type = type;
    if (this.type == 'rectangle') {
        this.shape = new p2.Box({ width: widthOrRadius, height: height });
    }
    else if (this.type == 'circle') {
        this.shape = new p2.Circle({ radius: widthOrRadius });
    }
    this.body.addShape(this.shape);
    world.addBody(this.body);
}
var bod1 = new PhysicsBody('circle', 0, 0, 32);
var bod2 = new PhysicsBody('circle', 10, 0, 32);


texts:
I have some bodies around the screen(Ball[] balls), and I would like to delete them when user touches them.

Also, I have an Image as userData of the bodies.

I dont want to make a function to all Image, because the balls have to be deleted in an order.

What is the best way to detect if a body is touch?


texts: Adding Screenshots Specifically For 4-inch, 7-inch, and 10-inch Screen

texts:
My boss invited me and assigned me now as publisher for the app in Google Play. I have a 7-inch Google Nexus 7 tablet to take screenshot of any one of my sample projects I've made and post and upload it into the 7-inch screenshot section. Now, I want to take some screenshots and post it this time into the 4-inch screenshot section. However, I got a 4.5-inch smartphone that runs on Android ICS.

I was wondering. Is it valid if I posted on the 4-inch screenshot section using all my snapshots taken from the 4.5-inch screenshot image or there is a specific requirement for that like the width and height in pixels?


texts: What different ways are there to model restitution in a physics engine?

texts:
In my physics engine I give a body a value for restitution between 0 and 1. When two bodies collide there seems to be different views on how the restitution of the collision should be calculated. To me the most intuitive seems to be to take the average of the two but some seem to take only the largest one.

Are there other ways to do it? Also, could the closing velocity or some other parameter come into effect?


texts: In a 2d tile based game, what is a good method for scrolling?

texts:
I am using Direct3D with the D3DXSPRITE wrapper to draw the tiles to the screen. I have a tile class which contains members such as collision and tile type, then i have an array of tiles e.g.

Tile grid[256][256];

Which would be a better method?

-Draw the player in the center of the screen and offset where the map draws.

-Move the player with the camera following.

I was using the first method, but its getting really complicated when you get to the top left edge of the map, and when other players/enemies are on the map and moving at the same time

if i make the camera follow the player, would i have to call spriteBatch->Draw(...) for every single grid tile even though only a few can fit on the screen?


texts: Actual Sizes of An Image loaded with a Path

texts:
I have a method which selects an Image from device. I need to show this image to users.

The codes below works fine, does what I need.

    Texture2D texture = new Texture2D(512, 512);
    texture.LoadImage(System.IO.File.ReadAllBytes(imgPath));
    texture.Compress(false);
    texture.Apply();

I just want to know how to change new Texture2D(512, 512) to real size of this Image.

Maybe this: new Texture2D(img.ActualWidth, img.ActualHeight)

Any idea?

Additionly is there any way to get original width and height from an Image loaded from a base64String ?

    byte[] imageBytes = Convert.FromBase64String(base64Str);
    Texture2D textureImage= new Texture2D(**250, 300**);
    textureImage.LoadImage(imageBytes);


texts: SmothStop Function doesn't work as expected

texts:
i'm trying to create a smothstop function i need it to control time variable on my lerp function used to move character and so on...what i have is this

    private float SmothStop(float t)
{
    return  1 - (1 - t * t * t * t * t);

}

problem here is that will start slow then accelerate... same as smothstart function.. that i already tested and work on that way.. so.. what i'm missing up?


texts: How can I create color fonts to be used in Unity?

texts:
I've been searching, downloaded a couple programs that lets you convert images into fonts, but none let you obtain the color. They all switch them to black and white.

While searching the internet, I found a few colored fonts. Yet, almost all games have their own fonts that are colorful.

How do they do it? Did they just opt to program the font with coded position and sizes?

I'd just like to make my own true type or open type font (ttf or otf) from some images I created. And the images aren't even that colorful, just fill and stroke color.


texts: Is keeping all my game art in a static class wasting memory?

texts:
When I make games, I generally create a static class called Art that has static fields to track all content in the game. For example

public static class Art
{
    public static SpriteFont defaultFont;

    public static Texture2D playerSprite;

    public static void LoadContent(ContentManager content)
    {
        defaultFont = content.Load<SpriteFont>("Fonts/DefaultFont");
        playerSprite = content.Load<PlayerSprite>("Sprites/PlayerSprite");
    }
}

My question is do these objects in my art class take up memory for the duration of the games lifetime? The point of this class is to only have to load my art once in the game and have easy access to the assets anywhere in my project, but at what cost?


texts: What benefits does a game design degree have for a hobby game programmer?

texts:
I am interested in studying game design, not because I want a job in the games industry, but because I am interested in the subject itself. I read the following questions, but they mostly deal with the effects on your career in game industry.

Should I consider a graduate degree in game development?
Game Development Degree vs Computer Science Degree

First I thought a game development degree could be beneficial. But from the websites of colleges that offer such degrees, I feel like its more about basic programming with examples from games.

This college offers game design degrees, for example.

My question is, can I benefit from such a degree when I already have a degree in Computer Science, I already know programming, I'm already developing a game and finally, I have this site to help me when I get stuck?


texts: How to use styles in Monogame.Extended.GUI?

texts:
So i was looking at the Monogame.Extended.GUI Project and used this instructions to set it up in a .net Core Project. So far everythings works fine. I followed the example of the demo and created a button like this

var button = new Button();
button.Content = "Button1";
button.BackgroundColor = Color.Transparent;

var demoScreen = new Screen
{
   Content = new StackPanel
   {
        Orientation = Orientation.Vertical,
        VerticalAlignment = VerticalAlignment.Centre,
        HorizontalAlignment = HorizontalAlignment.Centre,
        Items = { button }
   }
};

Now i want to give this Button a style, for example disable any mouse interactions like hover or mouse presses. The button has a HoverStyle and a PressedStyle property but i don't know how to use it.

   button.Hoverstyle = ???


texts: Run a physics simulation on both client and server?

texts:
I'm implementing a multiplayer asteroids clone to learn about client/server network architecture in games.  I have spent time reading GafferOnGames and Valve's publications on their client/server tech.  I am having trouble with two concepts.

Currently I have an authoritative game server simulating physics with box2d and sending out the state of the world to clients about 20 times per second.  Each client keeps track of the last few snapshots it received and lerps between two states to smooth out the movement of sprites.  However it's not that smooth.  It can be smooth for a while, then jerky a bit, then back to smooth, etc.  I have tried both TCP and UDP, both are about the same.  Any idea what my problem might be?  (Note: I implemented this for single player first, and the sprite movement is perfectly smooth at 60fps when updating the physics world only 20 times per second).

In order to solve the first problem I thought maybe the client should run a box2d simulation as well and just update the positions of its sprites to match the server snapshots when they don't match.  I thought this might be smoother since my single player implementation is smooth.  Is this a good idea?
Even if it won't fix the above problem, is it necessary for client-side prediction?  For example, if a player attempts to move their ship, how will they know if they hit an asteroid, wall, or enemy ship without a physics simulation?  It seems like their ship would appear to pass through the object it should collide with before they receive a snapshot from the server that says they hit the object.

Thanks!


texts: Need help choosing the right networking approach/platform for an RTS

texts:
I have been thinking for a while about making an online 2D RTS-like game. (2-6 players in a match, up to 50-60 units, no AI). The key thing here is that I want the game to be playable in a browser, so it'll have to be either flash or java applet, both using TCP sockets. At first I was entirely focused on flash because of a higher market penetration and accessibility. However, after reviewing different networking approaches I am unable to make a choice.

I really liked lock-step simulation approach where server and every client are running the exact same simulation, until I realized that it's going to be tough as hell (if not impossible) to implement exactly the same logic in two different languages, one of them being actionscript. This is where java comes in. With java client and server can share simulation related code - that may as well cut the development time in half.

But then there is another approach, where clients try to simulate (or rather extrapolate) the game state correctly as long as possible, but they don't have to do it right - at some point they are going to receive the full state snapshot an adjust accordingly. Flash looks like a viable option again, but still, lock-step simulation seems so much more straightforward, as there is no "adjusting" part.

So are my assumptions correct? What would you suggest?


texts: JoyStick::GetInfo(JoyStick::id1).dwButtonNumber always returns 0x1

texts:
I am using an XBox 360 gamepad for Windows.
I am having an issue with the following legacy code base, which relies on JOYINFOEX, JOYCAPS and MMRESULT:
ji.dwButtonNumber returns 0x1 no matter what button is selected (I suspect this is deprecated.) Update() is called in the Message Dispatch loop of my application. I am able to get the gamepad count, device driver name, its capabilities, etc. but am unable to get unique values for each button when it is selected, thoughts?
class JoyStick
{
public:

    enum JOYSTICK {id1, id2};
    JOYCAPS&          GetCaps      ( enum JOYSTICK id );
    static JOYINFOEX& GetInfo(enum JOYSTICK id);
    static UINT       GetStickCount( void );

//...

void Scene1::Update()
{
    JOYINFOEX ji;
    WPARAM key;

    ji = JoyStick::GetInfo(JoyStick::id1);
    key = theapp->GetKey();

    switch (ji.dwButtonNumber)
    {
        case GP_A :
        {
            TRACE("Button Number %i pressed\n", ji.dwButtonNumber);   // ji.dwButtonNumber == 0x1
            break;
        }
        case GP_B :
        {
            TRACE("Button Number %i pressed\n", ji.dwButtonNumber);     // ji.dwButtonNumber == 0x1
            break;
        }
        case GP_X :
//...
```


texts:
I've created an animation by using different frames. Then applied polygon collider on that object. Problem is that when frame changes in animation, it does not reset collider. I've searched for resetting polygon collider as sprite gets change. One solution I've found is like following :
Destroying existing collider & Adding new collider to the object.
http://answers.unity3d.com/answers/723811/view.html
I've applied this on the object. But it hangs the game. Is there any another way to reset polygon collider from c#.


texts: Send large amount of vertices to graphics card

texts:
I am programming at the moment a minecraft clone.

The advantage of this clone is that the whole world is handled as a model.
That means: The whole world is represented by 2d flat tiles and is uploaded to ONE vertex buffer.( therefore ONE drawcall)

The indices are stored seperatly in the hard drive because to re generate them every time the game starts is a bit overkill.

The loading time for a 64x64 ( 16x16x256 á la chunk) lies between 3 to 5 seconds.

The problem ist following:
I calculated the amount of vertices :
One VertexPositionTexture has a size of 20 bytes.
Multiplied by 8702348 ( because of 8702348 vertices ) the whole amount sent to the graphics card is over 160 MB !

It's no problem for the graphics card: Constant 60 FPS... but I am intended to _ implement infdev. This means the game has to upload frequently over 160 MB to the graphics card: Pure overkill.

I want to avoid using a vertex buffer for each chunk in order to have a single draw call.

Can you suggest a solution?

Thanks.

The project can be found on https://github.com/NET-D3v3l0p3r/XChunk/tree/master/Chunk


texts:
I am trying to create a transmittance or absorption shader (glsl, hlsl, cg, etc...) in realtime but I don't find any good tutorial or white paper about this subject. I only find offline rendering references.

Is it possible to achieve this kind of effect in realtime using standard rasterisation of a 3D mesh ? How ?


texts: How to enable CrossPlatformInput in Unity?

texts:
I'm new to Unity but not a complete programming novice.

I'm trying to use the CrossPlatformInput component from the "Car" prefab from Standard Assets.

I can't see it appear and when reading the notes file it says this:

  Importing the CrossPlatformInput package adds a menu item to Unity, "CrossPlatformInput", which allows you to enable or disable the CrossPlatformInput in the editor. You must enable the CrossPlatformInput in order to see the control rigs in the editor, and to start using Unity Remote to control your game.

So,

What is "a menu item" and where do I find it in the Unity UI?
How do I enable CrossPlatformInput? I have dragged the prefab called DualTouchControls into my scene but I can't see anything and I'm not sure how to link it to the actual car object.


texts: How can I resolve this error I'm getting in my movement script?

texts:
For my player controlling script, I have attempted to do it so the player can only jump two times, I've not had any errors in the script itself but when I save it and go back on Unity, the error I keep getting is this:

  error CS0120: An object reference is required for the non-static field, method, or property Collision.gameObject

This is my code:

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

public class playerController : MonoBehaviour
{
    public float speed;
    public float power;
    private Rigidbody2D rb;
    int numberofJumps = 0;
    public int doubleJump = 2;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        numberofJumps = doubleJump;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            rb.AddForce(Vector3.right * speed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            rb.AddForce(Vector3.left * speed);
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            if (numberofJumps > 0)
            {
                Jump();
            }
        }
    }

    public void Jump()
    {
        rb.AddForce(Vector3.up * power, ForceMode2D.Impulse);
        numberofJumps -= 1;
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (Collision.gameObject.tag == "ground")
        {
            numberofJumps = doubleJump;
        }

    }
}

The error seems to be specifically regarding this line:

if (Collision.gameObject.tag == "ground")


texts:
I have two scripts, a server script and a client script.
I built two parts of the app, one with the client script and another one with the server script.
I put both apps on devices, connected two devices with the local network and run the server.
First I wrote this line in the client to get the IP of the server device:

NetworkManager.singleton.networkAddress

But it gives me the IP of the client device.
Do you have any solution to this problem?

Thanks.


texts: Unity2D - Placing text HP and health bar over character sprite

texts:
I've got a 2D character sprite that I will move through a game board. I want to add over it, in a corner of the sprite, a Text object with the remaining HP of that character and also a health bar. I want those elements to move with the Character. Wherever the character moves, the UI follows.

I've tried adding a Text element in World Space and attaching it to the character sprite, but the Text is so huge that it's not displayed properly on top of it. I need to know how to adapt that text to the size of the sprite and how to make it follow it automatically. I guess that by setting the ch sprite as parent of the Text/canvas it would work, but I don't know how to get it working.

Thanks in advance


texts: How to remotely host my c++ game server on Ubuntu?

texts:
I made a server for a 3D multiplayer game I'm working on. The game is currently functional to a point where I know multiplayer gameplay is possible locally on Windows.

IDE: Visual Studio 2019
Target platforms: Windows & Ubuntu
Server linked libraries: winmm.lib, ws2_32.lib, sfml-system-s-d.lib, sfml-network-s-d.lib

I want the server to work on a remotely hosted dedicated server where I have Ubuntu installed, and to be capable of connecting the client locally from Windows, how should I do this? Considering the following:

My project currently uses the visual C++ compiler from VS,
which I presume makes my own c++ code only work on windows (correct?).
I've done some simple aplications for Ubuntu in C++, and know that
for an aplication to work on Ubuntu, it needs to be compiled using
the g++ compiler, however, this doesn't seem to be an option on my
current environment.
Also, 2 of the libraries my sfml dependencies depend on, seem to be
designed for windows (This could mean issues with the sfml modules I'm
using?).
Finally, I also know there could be some endianness issues, for now
I did a quick check and found out both my local, and remote cpu's,
use little endian formats.

Additional note: I really could just install any other OS on my remote machine, including Windows, but I like Ubuntu's lightweightness, and I'm familiar with the OS.


texts:
I am trying to get a turret to rotate on a 90 degree arc (rotating about 2 orientations about the y-axis), and have hit a wall.

I have 8 possible starting orientations (multiples of 45 degrees about the y-axis) for the turrets, and want them to rotate on a 90 degree arc. I currently take the starting orientation of the turret, and then from that derive the positive, and negative boundary of the arc. because of engine feature/restriction (Unity) I have to do all of my tests against a value which is between [0,360], and due to numerical precision  issues I can not test against specific values, but should only limit tests to greater, and less then operators.

I would like to write a general test without having to go in, and jury rig cases

//my current test is:
// member variables
public float negBound;
public float posBound;

// found in Start() function (called immediately after construction)
/* because Unity uses a Quaternion for orientation of object they offer
 * the ability to work with them in the form of eulerAngles.
 * eulerAngles.y is the the degree measure of the starting y rotation */
negBound = transform.eulerAngles.y-45;
posBound = transform.eulerAngles.y+45;
// insure that values are within bounds
if(negBound<0){
    negBound+=360;
}else if(posBound>360){
    posBound-=360;
}

// called from Update() when target not in firing line
void Rotate(){
    // controlls what direction
    if(transform.eulerAngles.y>posBound){
        dir = -1;
    }
    else if(transform.eulerAngles.y < negBound){
        dir = 1;
    }
    // rotate object
}

follows is a table of values for my different cases (please excuse my force formatting) read as base is the starting rotation of the turret, neg is the negative boundry, pos is the positive boundry, range is the acceptable range of values, and works is if it performs as expected with the current code.

| base | neg | pos |       range        | works |
|    0 | 315 |  45 | 315->0,   0->45    | no    |
|   45 |   0 |  90 | 0->45,    54->90   | yes   |
|  135 |  90 | 180 | 90->135,  135->180 | yes   |
|  180 | 135 | 225 | 135->180, 180->225 | yes   |
|  225 | 180 | 270 | 180->225, 225->270 | yes   |
|  270 | 225 | 315 | 225->270, 270->315 | no    |
|  315 | 270 |   0 | 270->315, 315->0   | no    |

I will need to do all tests from derived, or stored values, but can not figure out how to get all of my cases to work simultaneously.

//I attempted to concatenate the 2 tests:
if((transform.eulerAngles.y>posBound)&&(transform.eulerAngles.y < negBound)){
    dir *= -1;
}

this caused only the first case to be successful

// I attempted to store a opposite value, and do a
void Rotate(){
    // controlls what direction
    if((transform.eulerAngles.y > posBound)&&(transform.eulerAngles.y<oposite)){
        dir = -1;
    }
    else if((transform.eulerAngles.y < negBound)&&(transform.eulerAngles.y>oposite)){
        dir = 1;
    }
    // rotate object
}

this causes the opposite situation as indicated on the table.

What am I missing here?


texts: How can I process continuously-held keys with SDL?

texts:
I have created a cube in opengl using SDL. Now I am trying to move the camera in X direction if user presses left or right arrow keys and Y direction if user presses up or down arrow keys. Right now the camera moves by a fixed amount in a particular direction if the key gets pressed once. It doesn't matter how long does a person hold the key down, it moves by that fixed amount only. I want the camera to move continuously as long as the key is pressed.

Below is the code for keyboard polling.

        while ( SDL_PollEvent( &event ) )
        {
            switch( event.type )
            {
            case SDL_ACTIVEEVENT:
                if ( event.active.gain == 0 )
                isActive = FALSE;
                else
                isActive = TRUE;
                break;
            case SDL_VIDEORESIZE:
                surface = SDL_SetVideoMode( event.resize.w,
                            event.resize.h,
                            16, videoFlags );
                if ( !surface )
                {
                    fprintf( stderr, "Could not get a surface after resize: %s\n", SDL_GetError( ) );
                    Quit( 1 );
                }
                resizeWindow( event.resize.w, event.resize.h );
                break;
            case SDL_KEYDOWN:
                handleKeyPress( &event.key.keysym );
                break;
            case SDL_QUIT:
                done = TRUE;
                break;
            default:
                break;
            }
        }

And below i have mentioned the keypress handler function

void handleKeyPress( SDL_keysym *keysym )
{
    switch( (keysym->sym) ){
        case SDLK_ESCAPE:
            Quit(0);
            break;
        case SDLK_LEFT:
              eye[0] -= 0.1;
              break;
            case SDLK_RIGHT:
              eye[0] += 0.1;
              break;
            case SDLK_UP:
              eye[1] -= 0.1;
              break;
            case SDLK_DOWN:
              eye[1] += 0.1;
              break;
            default:
              break;
      }

    return;
}

What changes should I make in my code to handle continuous keystroke detection?

Note:
The following code does the required job but I don't understand why

if ( ( SDL_EnableKeyRepeat( 100, SDL_DEFAULT_REPEAT_INTERVAL ) ) )
{
        fprintf( stderr, "Setting keyboard repeat failed: %s\n",
             SDL_GetError( ) );
        Quit( 1 );
}


texts: I'm working on "Scorched earth"-like game just for learning purpose. I can't figure out how to launch the projectile from my tank's position, with a power of X ([0,100]),at an angle of Y ([-180,180]).


texts: Insert 3d text to the front face of a cube GameObject

texts:
I want to add a text to a cube in Unity.

I have a cube which has a 3d text as a child.

I am using the below UnityScript to write on the 3d text:

var countdown : int = 200;

function Update()
{
    GetComponent(TextMesh).text = countdown.ToString();
}

I am trying to write/show the text to the front face(or very close) of the cube but I am failing.

EDIT: My difficulty is to make the text appear in the front side/face of the cube, like it is written on it. Attaching the text or the script to any object is not an issue

My last failed try was to use the below lines:

var tm = gameObject.AddComponent(TextMesh);
tm.text = countdown.ToString();

Any ideas?


texts: Load all sprites up-front, or stream them?

texts:
I'm currently in the starting phase of my first large game in Swift and SpriteKit. It will be a Super Mario-like platformer game where each level is about two minutes long.

Since I've never made a game like this one before, I don't have much experience about how to make games effective and RAM-friendly.

I'm wondering if I should load every single SpriteNode immediately as the player launches a level, or if I should render these as the player advances through the level.

Loading everything instantly seems easier and more straightforward, but will this have a large effect on performance?


texts: Moving camera vertically only after player is too high or too low

texts:
In my 2D platformer game, I find it very exhausting for the player if the camera follows the player all the time. So, I looked up for some tricks to make camera movement feel more natural.

The first trick is from James Doyle, where the camera follows a target instead of the player itself. Thus, I can safely use Mathf.Lerp for the target, and avoid having jitters.

The second thing I want to do is to limit the vertical movement of the camera. That is, I don't want the camera to move up and down whenever the player jumps. It is dizzying.
Instead, I want camera to follow the player only if player is vertically too high or too low.

Here is roughly what I do:

\\PlayerController.cs

    public Transform cameraTarget;
    private void FixedUpdate()
    {
       if(Mathf.Abs(transform.position.y - cameraTarget.position.y) > verticalLimit )
         cameraTarget.position = new Vector3(cameraTarget.position.x, Mathf.Lerp(cameraTarget.position.y, transform.position.y, Time.fixedDeltaTime), cameraTarget.position.z);
        if (Input.GetAxisRaw("Horizontal") != 0)
        {
            cameraTarget.localPosition = new Vector3(Mathf.Lerp(cameraTarget.localPosition.x, Input.GetAxisRaw("Horizontal")* cameraAheadAmount, 0.8f * Time.fixedDeltaTime), cameraTarget.localPosition.y, cameraTarget.localPosition.z);
        }

    }

The problem for this approach is that whenever the vertical distance between the player and the camera target is less than the limit, the camera does not follow the player anymore.
So, what I get is basically a camera following the player from down below, again, all the times.

I thought of using a boolean flag to tell the camera follow the player when vertical limit is exceeded, but then when do I set and unset the flag?

I am new to Unity's Update() and FixedUpdate() logic, so I cannot somehow design a workaround. Is there a simple way to do this?


texts: How do you use custom collision on a skeletal mesh in UE4?

texts: I have a vehicle rig that is a skeletal mesh that imports fine in to unreal but I was wondering how to use a mesh for collision on it. Normally you can just name the collision mesh with UCX_ in front of the name to do it but with skeletal meshes it makes you use a system called phat and I only see cubes/spheres/capsules for collision with that.


texts: Controls for physics-enabled game object

texts:
I'm trying to put together 2D game on Flash ActionScript. Game objects positions are updated by physics library and I'm trying to control them applying forces and updating these forces every frame.

Right now I'm pondering how to control a helicopter. I'm using concept of throttle and target height. To make heli float on constant height, I'm applying force of

F0 = -m * gy

which negates gravity for it. To make it move up or down, target height is used - it is increased with up key and decreased with down key, then the heli should ascend or descend to it. The problem is transitional process - right now the heli misses target height and then oscillates around it.

In short: how to control body with forces to make it move from point A to point B and stop there?
Here's how I'm controlling it now:

    public function update(time:int):void
    {
        lastUpdate = time;
        var deltaY:Number = targetHeight - body.graphic.y;
        throttleMark.y = targetHeight;
        //force for stable floating
        var antigrav:Number = -body.gmass * body.space.gravityy;
        //made-up damping factor
        //   (in fact, too small, but higher scale make heli move very slowly)
        var damping:Number = -body.vy * body.vy * body.vy * 0.5;
        var attraction:Number = deltaY * 1000.0;
        var totalForce:Number = antigrav + attraction + damping;
        body.applyRelativeForce(_strafe, totalForce, 0.0, 0.0);
    }