texts: Custom shadowmapping in Unity not working properly

texts:
To experiment with a certain technique, I'm implementing my own shadow mapping in Unity. I'm using a camera for the light "view", which is rendered to a RenderTexture after being post-processed with the following shader:

Shader "Custom/DepthGrayscale" {
  SubShader {
     Tags { "RenderType"="Opaque" }

     Pass{
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        sampler2D _CameraDepthTexture;

        struct v2f {
           float4 pos : SV_POSITION;
           float4 scrPos:TEXCOORD1;
        };

        //Vertex Shader
        v2f vert (appdata_base v){
           v2f o;
           o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
           o.scrPos=ComputeScreenPos(o.pos);
           //for some reason, the y position of the depth texture comes out inverted
           o.scrPos.y = 1 - o.scrPos.y;
           return o;
        }

        //Fragment Shader
        half4 frag (v2f i) : COLOR{
           float depthValue = tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(i.scrPos)).r;

           return fixed4(depthValue, 0.0, 0.0, 0.0);
        }
        ENDCG
     }
  }
  FallBack "Diffuse"

}

With a width and height of 2048 for the Render Texture and the color format R Float for 32-bit precision.

The objects in the scene then have the following shader that takes the projection * view matrix of the light and "depth" texture as input. (Basic shadow mapping with bias)

Shader "Tutorial/Display Normals" {
    Properties {
        _CameraTex ("Camera texture", 2D) = "white" {}
    }
    SubShader {
        Pass {

            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            uniform float4x4 lightMatrix;

            struct v2f {
                float4 pos : SV_POSITION;
                float3 worldPos : COLOR0;
                fixed3 color : COLOR1;
            };

            v2f vert (appdata_base v)
            {
                v2f o;
                o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
                o.worldPos = v.vertex.xyz;
                o.color = v.normal * 0.5 + 0.5;
                return o;
            }

            uniform sampler2D _CameraTex;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 coords = mul(lightMatrix, fixed4(i.worldPos, 1.0));
                coords /= coords.w;

                coords.x = (coords.x + 1.0) / 2.0;
                coords.y = (coords.y + 1.0) / 2.0;
                coords.z = (coords.z + 1.0) / 2.0;

                //return fixed4(coords.z, 0.0, 0.0, 1);
                float lightDepth = tex2D(_CameraTex, fixed2(coords.x, 1.0 - coords.y)).r;
                float depth = coords.z;

                if (depth < lightDepth + 0.005) {
                    return fixed4(1.0, 1.0, 1.0, 1.0);
                } else {
                    return fixed4(0.1, 0.1, 0.1, 1.0);
                }
            }
            ENDCG

        }
    }
}

The result of this is perfect with a plane and cube:

The red plane displays the shadow map and the camera represents the light.

However, when using a more complex model like Sibenik, the following happens:

When I move it slightly, the shadow on the plane is suddenly correct, but the shadow on the church model itself is still wrong:

What could be the problem?


texts:
I'm using box2d and I simply hook up 10 points each with a similar length constraint to the adjacent point.

When I move 1 point, the others follow just like a rope/chain. Just like one would expect.

What I would not expect however is that when I fix the leftmost point and then pull the right most, the points distribute themselves very odd. When I simulate it using ascii it is as following:

OO-O--O---O----O-----O------O-------O--------O

I would have prefered that one point would 'win' (given the order of point creation or something) and that the rest of the points would never reach the other point (due to their constraints).  Or maybe even that the points would distribute themselves in a better fashion.

Does anyone have an explanation on why this is and how this might be solved?


texts: Programmatically create a trigger within abnormally shaped room

texts:
So I'm trying to create a trigger in each of my rooms. These rooms can be created by players. Basically, I need to know all the objects in a room. These rooms can be shaped in weird and wonderful ways. I'm struggling to figure out how to "fill" an area? The other problem is that some walls are curved.

My current thinking is:

Loop over all the walls in a scene. Do 4 raycasts from each side of the wall and see if we hit other walls. If we do, we are likely in a room.
From the offset, literally check each node adjacent to that until we fill the room. Once I have this though, Im not sure what to do with it.

How do I create bounds that I can check for collisions with this data?

Edit: Adding an image for clarity. Red and blue should be 2 different rooms and I want to get all items in each of these rooms


texts: 16bit triangle lists vs 32bit triangle strips

texts:
When drawing geometry we may use indexed drawing, where we pass index of the vertex we want to draw in array. In this case we need to pick a topology for our geometry and the type of indices.
Popular topologies are triangle lists, where we have to specify 3 indices for each triangle, and triangle strips, where each new triangle shares its first 2 vertices with last 2 vertices of previous triangle.
As for index types - we have 16 bit indices, which allow for ~65k vertices per model, and 32 bit indices, ~4B vertices.
My GPU (1050ti) fetches 32 bit indices at half the rate of 16 bit indices, where 16 bit indices triangle list topology gets it at its maximum throughput, but so do 32bit triangle strips. As my GPU isn't that old, I expect many GPUs to be quite alike in this manner.
So, is the inconvinience of having to specify geometry in strips worse than having a limit to 65k vertices per model?


texts: How can animate a set of rigs without reinventing the wheel?

texts:
I have a set of rigs of my own defined 3D doll in Javascript. I would like to animate a set of rigs to simulate walking, jumping, etc. Obviously I could do it by myself, but I'm sure I would be reinventing the wheel.

Are there algorithms, libraries (won't matter the language) or anything that I can download and it will give me the position of the rigs in function of time for many animations like walking, jumping?


texts: Low traffic client synchronization with server in MMO

texts:
I am implementing MMO where player flies in space on his starship controlling it with arrow keys and cooperate with other players.

I want to implement it so that player will be able to dodge his ship from rocket or something else, so I am trying to predict whole game state on client side using the same world simulating algorithm as server use. That game world is written on C# and will be called within client directly (it's written on Unity3D) and through CLR on C++ server (under Linux). Connection through UDP.

Problem is how to maintain, for example, 1000 players within single map (exclusing all other game objects, mobs...):
Let's say I will:

synchronize server with clients 50 times per second
send to each client states of just that game objects (and players) which he is able to see (within some radius)
have to send 100 objects to each player within his view radius
must send averagely 50 bytes per game object (it's id, x,y coords, rotation, state...)

so, it will need to have such network bandwidth: 1000 (clients) * 50 (times per second) * 100 (objects to send to each player) * 50 (bytes per object) = 250 000 000 bytes per second! It's impossible!

Is it possible to reduce this value somehow? For example let clients to fully simulate their game worlds (for a long period of time) and send them just inputs of other clients and synchronize game worlds, let's say, each several seconds but it will cause weird desynchronization issues at leash because of float computations.

Anyway, how such games are programmed in common way? Thank you.


texts: Can't figure get the conversion from cartesian to spherical("polar") correctly for my orbiting camera

texts:
The two angles from the polar coordinate system are defined as hRotation and vRotation

This is how they are converted from polar to cartesian:

    // Get the distance between the object and the camera
    float distance = cam.getLocation().distance(RotationTarget);

    Vector3f pos = new Vector3f(distance * FastMath.sin(vRotation) * FastMath.cos(hRotation),
                                distance * FastMath.cos(vRotation),
                                distance * FastMath.sin(vRotation) * FastMath.sin(hRotation));

    // Add in the objects position to make the new relative position of the camera
    pos = pos.add(RotationTarget);
    cam.setLocation(pos);

Now the problem is when I try to get hRotation and vRotation from cartesian coordinates for the to initialize hRotation and vRotation, rather than setting them to an arbitrary value and having the camera jump each time. The camera is generally free roaming "a fly cam" but when an object is selected, the user can hold shift to rotate the camera around the object. So I need to base hRotation and vRotation off of the coordinates of camera and object, here is my code so far, but the issue is that the Camera will mirror its rotation rather than allowing me to fully rotate. For instance I can rotate to the left but it snaps to opposite angle from the right. I know I probably need to invert the angle when something is less than something, but I can't figure out what it is...

    float distance = cam.getLocation().distance(RotationTarget);

    Vector3f diff = cam.getLocation().subtract(RotationTarget);

    vRotation = FastMath.acos(diff.y / distance);
    hRotation = FastMath.asin(diff.z / FastMath.sqrt((diff.x * diff.x) + (diff.z * diff.z)));

Thanks,
-Tim


texts: Camera movement issue with pitch and yaw angles

texts:
I'm trying to implement a simple first person camera using pitch and yaw angles (no quaternions, I want a simple camera for debugging purposes). An Input class processes mouse input and translate the x and y position in the window into angles. Here's the code:

#define SENSITIVITY 0.01f

void Input::ProcessMouseInput(int x, int y, Camera &camera)
{
    /* pitch and yaw angles */
    static float pitch = 0;
    static float yaw = 0;

    /* initialize initial mouse position */
    static int prev_x = x;
    static int prev_y = y;

    int offset_x = x - prev_x;
    int offset_y = y - prev_y;

    pitch += offset_y * SENSITIVITY;
    yaw += offset_x * SENSITIVITY;

    /* compute transformation matrix */
    XMMATRIX pitchTransform = XMMatrixRotationX(pitch);
    XMMATRIX yawTransform = XMMatrixRotationY(yaw);
    XMMATRIX transform = XMMatrixMultiply(pitchTransform, yawTransform);    // fps-like
    //XMMATRIX transform = XMMatrixMultiply(yawTransform, pitchTransform);  // airplane-like

    /* transform camera direction - rotate camera */
    XMVECTOR oldDirection = XMVectorSet(0.0, 0.0, 1.0, 1.0);
    XMVECTOR newCameraDirection_ = XMVector3Transform(oldDirection, transform);
    XMMATRIX oldView = XMLoadFloat4x4(&camera.GetInitialViewMatrix());
    XMVECTOR det = XMMatrixDeterminant(oldView);
    XMMATRIX inverse = XMMatrixInverse(&det, oldView);
    XMVECTOR v = XMVector3TransformNormal(newCameraDirection_, inverse);
    XMFLOAT3 newCameraDirection;
    XMStoreFloat3(&newCameraDirection, v);
    camera.SetDirection(newCameraDirection);

    /* store current mouse position */
    prev_x = x;
    prev_y = y;
}

What I do is I calculate the direction vector in the view space and transform it with pitch/yaw rotations. Then I tranform the resulting vector in world space coordinates and update the camera direction. All works fine if the camera space x-z plane initial position  is parallel to the world space x-z plane. If the camera is initially tilted downwards or upwards the movement is off (moving along the yaw direction causes a wobbling and the movement is incorrect).
I can't find the problem as I think the calculations are correct (but they obviously aren't).

EDIT

what I mean with odd behaviour is that when I create a camera that has starting position with a pitch wich is not zero I get mixed movements (pitch when yawing and yawing when pitching)


texts: Best way to traverse triangles in a mesh

texts:
I'm implementing non-projective decals. As described in many places (ie: lengyel in the gpg2) I first need to detect all triangles that lie within some sort of frustum.

Besides obvious brute-force solutions (ie: checking each triangle), what are better ways to generally search triangles in a mesh?
One solution i can think of is, for each mesh, keep some parallel data structure better suited for searching. are there any well know algo/solutions?


texts: I am developing for Android.In my game data is in objects which aren't derived from MonoBehaviour.So I am using binary serializer and taking references from the gameobject.It works, but I have too many variables to save most of variables are in script attached to gameobject Gamemanager So I made a prefab of gameobject of Gamemanager and saved it using prefabutility and load it again It works but Can someone tells me whether this is right approach or not, please??


texts: Need help with a complex 3d scene (using Ogre and bullet)

texts:
In my setup there is a box with a hole on one side, and a freely movable "stick" (or bar, tube). This stick can be inserted/moved through the hole into the box. This hole is exactly as wide as the diameter of the stick.

In reality, when you would now hold the end of the stick in your hand and move the hand left/right or up/down, the other end of the stick, which is inside the box, would move into the opposite direction of your hand movement (because the stick is affixed at the pivot point where it is entering the box through the hole).

(I hope you understand what I mean so far.)

Now I need to simulate such a setup in a 3d program. I have already successfully developed an Ogre3d framework for this application, including bullet. But what I don't know is how I can implement in my program what I have described above. This application must include two more features:

The scene camera is attached to the end of the stick that is inserted into the box. So when the user would move the mouse (to control "his" end of the stick outside the box), then the camera attached to the stick would move in the opposite direction, as described above.
The stick has some length, and the user can push it further into the box, or pull it closer to him again. That means of course that the max. radius on which the end of the stick inside the box can move depends on how far the stick is pushed into the box. Thus, the more the stick is pushed into the box, the larger the max. radius of this end of the stick with the camera will be.

I understand this is maybe quite a complex thing, so I don't expect any real source code here. I already have the Ogre and bullet part as said up and running, as well as a camera attached to the stick. This works fine. What I don't know though is how I can simulate the setup described above. Especially the requirement that the stick is affixed at the position of the hole on the box, where it is inserted into the box.

Any ideas how I could approach to implement the described setup?


texts:
I have a question about Bullet and in particular GImpact.

When, the collisiontestpair(a, b) is called where GImpact pair check algo will be called on the
btGImpactMeshShape, does it do a AABB tree vs. AABB tree to get to the leaf level, worstcase O(NN) OR is it O(NN) triangle wise collision check.

Thank you.


texts: 3D terrain generation with overhangs/caves

texts:
3D terrain with 2D noise function as heightmap is kind of 'easy'. Make a plane and adjust height based on the noise.

How would one start working on 3D terrain with overhangs/caves?

There are some older topics (for example related to Minecraft) on the thema, but non of them cover overhangs and in general techniques that can be applied to heightmap generated terrain.


texts: Is it possible to calculate the TBN matrix in the fragment shader?

texts: Just from model position, model normal and texture uv?


texts: How to create custom methods for sprite groups in pygame?

texts:
I want to use sprite groups in my game using pygame and the default draw isn't enough. I have tried some tutorials but I failed.

So, being more specific: I want to create custom methods for sprite groups in pygame such as .handle_event (this method can exist at all sprites or not).


texts:
I am not pro on programming and games but i had developed an online browser-based game with php . Now i am creating a game like a chess that it do not needs an live-stream and FPS data exchanges.

I want to know is my knowledge about php and tcp protocol is enough to develop such a game ? or i need to develop on other language and do not use tcp protocol ( use UDP instead ) .

And one thing more ... Can i develop with php on a UDP protocol ? where can i get little information about udp and programming on it.

thank you very much :)


texts: How to smooth mask texture edges correctly regardless it's size

texts:
I have a texture intended as a mask. The texture type is GL_R32F (32 bit float) and the data inside is a signed distance field (= value of each texel is distance to nearest mask edge). For test purposes, the mask is just a circle part and is directly drawn in greyscale. The fragment shader handling this texture has following code:

void main() {
 float mask = texture( tex, fragTexCoord).r;
   vec4 res = vec4(1.0,1.0,1.0, 1.0);

   if(mask > 0.0) //test failed, outside of mask
      res = vec4(0.0,0.0,0.0, 0.0);
   //smoothing if there is an edge nearby
   //0 or 1 otherwise
   res.w = smoothstep(0.0, 1.0, -1.0 * mask);
   finalColor = res;
}

however if the mask is drawn too big, its edges appear blurry, because smoothstep afflicts too many fragments. This could be solved by multiplying the mask by some value, however it would stop smoothing if is the mask was drawn too small.
For illustration, on left is the mask(100px), in the middle is its zoomed edge and on right there is zoomed edge of mask if drawn big(600px). How to smooth the edge to appear correct regardless of the size? (=zoomed edges should always look the same, like the middle image)


texts:
I have created a simple game and there are zombies as my enemies.If the distance of The player(Which is me) and the zombie less than 10,The zombie starts walking towards me.and there is a Cylinder object around me.I have turned off the Mesh Renderer of that cylinder so that it is invisible. And also there is a mesh collider in the Cylinder.
If the zombie reaches the cylinder , it starts to attack me and stops walking.But walking animation is still working.

How can I fix this, I need to stop walking animation of the zombie when it reaches the cylinder.Here is my code,

using UnityEngine;
using System.Collections;

public class ZombieFollow : MonoBehaviour
{

    public GameObject ThePlayer;
    public float TargetDistance;
    public float AllowedRange = 10;
    public GameObject TheEnemy;
    public float EnemySpeed;
    public int AttackTrigger;
    public RaycastHit Shot;

    void Update()
    {
        transform.LookAt(ThePlayer.transform);
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
        {
            TargetDistance = Shot.distance;
            if (TargetDistance < AllowedRange)
            {
                EnemySpeed = 0.01f;
                if (AttackTrigger == 0)
                {
                    TheEnemy.GetComponent<Animation>().Play("Walking");
                    transform.position = Vector3.MoveTowards(transform.position, ThePlayer.transform.position, EnemySpeed);
                }
            }
            else
            {
                EnemySpeed = 0;
                TheEnemy.GetComponent<Animation>().Play("Idle");
            }
        }

        if (AttackTrigger == 1)
        {
            EnemySpeed = 0;
            TheEnemy.GetComponent<Animation>().Play("Attacking");
        }
    }

    void OnTriggerEnter()
    {
        AttackTrigger = 1;
    }

    void OnTriggerExit()
    {
        AttackTrigger = 0;
    }

}

Here ThePlayer Gameobject is me and TheEnemy is the zombie.Walking, Idle and Attacking are the animations.


texts:
I have published a game on googleplay that uses Unity rewarded ads. Once the player dies, they have an option of reviving by watching a rewarded ad. However when I try this, the ad shows only 3 or 4 times and then nothing happens after that(when I click the revive button). Here is the ad manager script:
string GooglePlay_ID = "123456";
bool test_mode = false;
string myPlacementId = "rewardedVideo";

void Start()
{
   Advertisement.AddListener(this);
   Advertisement.Initialize(GooglePlay_ID, test_mode);
}

public void DisplayVideoAD()
{
    Advertisement.Show(myPlacementId);
}

public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{

    if (showResult == ShowResult.Finished)
    {
      GameManager.instance.ReceiveReward();
    }
    else if (showResult == ShowResult.Skipped)
    {

    }

    else if (showResult == ShowResult.Failed)
    {
        Debug.LogWarning("The ad did not finish due to an error.");
    }
}

 public void OnUnityAdsReady(string placementId)
{

    if (placementId == myPlacementId)
    {

    }
}

public void OnUnityAdsDidError(string message)
{

}

public void OnUnityAdsDidStart(string placementId)
{

}

Here is the ReceiveReward() function that's in the game manager. This function seems to work fine as after clicking the button, the game restarts with the score before the player died.
public void ReceiveReward()
{
    savedScore = (int)playerScore;
    UpdateUI(GameStates.Start);
    SceneManager.LoadScene(1);
}

I'm not sure what's going wrong as the ads work a few times...Can someone please help?


texts: Showing Frame Rate Info in the Unity scene using Custom Script failed

texts:
I want to lock the framerate of my scene to 30fps, then I learned from this post that fps info in Editor Stat isn't reliable, that's why my fps is still around 100. This is my script for setting the framerate (vSync also has been set into Don't Sync) :

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

public class TargetFramerate : MonoBehaviour {
    public int frame_rate = 30;

    void Start () {
    }

    void Awake (){
        QualitySettings.vSyncCount = 0;
        Application.targetFrameRate = frame_rate;
    }

    void Update () {
        if (frame_rate != Application.targetFrameRate) {
            Application.targetFrameRate = frame_rate;
        }
    }
}

But it doesn't work. Where should I put this script ? The description says in any GameObject will be ok, so I put in one of my GameObject with camera attached on it. By the way, I'm also using SteamVR camera script for my GameObjects (for HMD device), is it affecting this script ?

[UPDATE]

I posted the same question on Reddit, and got several feedbacks. So, the code that I used before from Wiki Unity 3D - FramePerSecond is outdated and using deprecated OnGUI system. As of now I'll try to use FPSCounter from the Standard Assets and see if it works.

Here's how it looks like on the scene using FPSCounter from Standard Assets, it works on the Game tab, but it doesn't show on the device (I'm using HMD- HTC Vive).

Also, my framerate lock code above doesn't seem to work, since the FPS is still reaching 90fps. Any advice ?


texts:
I'm creating a script to dynamicly load a menu with buttons.
On every button there is a script that need to be run when the button has been clicked. For the button there is a prefab where the script in enabled on. After instantiating the prefab the script on it has been disabled. When I manually enable it by code it does nothing. When enabling the script using the editor it does wor.

My code for generating the buttons on my menu looks like:

 foreach (BuildingModel model in models)
    {
          GameObject tempButton = Instantiate(buttonPrefab);

          PlaceObjectToScene script = tempButton.GetComponent<PlaceObjectToScene>();

           script.objectName = model.modelLocation + "/" + model.modelName + ".fbx";

           script.gameObject.SetActive(true);
            script.enabled = true;

            tempButton.transform.SetParent(horizontalLayoutGroup.transform);

    }

I searched on the internet for some answers and found forum thread with the same issue but non of the sollutions works in my situation. Can someone help me how to enable the script that is default enabled on the prefab?


texts: Does `yield return false;` have special meaning in Unity3d C# scripts?

texts:
In Unity, we have some special things for coroutines that are additional to normal C#.

for example, we can use

yield return WaitForSeconds(5.f);

to have a coroutine wait 5 seconds before continuing.

What do yield return false; and yield return true; do?


texts: How can I randomly pick points on a triangle?

texts:
Please can help me for a geometry query, I am working out fast mesh to voxel algorithm without using rays and complex maths...

What are the maths to sample N points on a triangle randomly? If you can sample randomly i think it means you know the same equation that can distribute points on a triangle at same spacing.

I found some info here but it's too difficult to understand:

https://math.stackexchange.com/questions/18686/uniform-random-point-in-triangle

http://mathworld.wolfram.com/TrianglePointPicking.html

The reason is to sample N points on every triangle and round each into a voxel space and send the rounded position of every sample as a true value to a boolean spacial voxel array of X,Y,Z true false values to represent voxels.

Thanks for any info's you may provide!


texts: What would be the most efficient mechanism to implement branching choices?

texts:
I am developing a Windows game engine that will let you create games styled like "Phoenix Wright: Ace Attorney". I have finished developing the data entry parts (evidence, profiles, animations, etc.), and now I am going to create the scene editor. With this editor, you can create courtroom scenes.

I am having a particular game-flow design problem with "choice branches", where the player can select an option from many, and something will happen depending on the choice. How should I design such thing? I have no problems creating a linear flow (action, action, action, etc.), but I am confused by things like cross-examination or chatting involve branching choices (action; if did something, do this; if did something else, do that; etc.).

What would be the most efficient mechanism to organize such branches for my design, in the simplest way for the user to understand? I don't want to make it too complex for the user to make a game with the engine.


texts: Designing interface for interacting with game objects

texts:
I'm making a roguelike (-like) game, somewhat like Project Zomboid or Don't Starve. In my game, there are many different object in the world that the player can interact with; there are also many items, some of which may be required for a particular interaction.

Physically, all I have to trigger the interaction is the mouse click: when player clicks on an object, something happens (adding right-click is an option too, but staying with just one button is preferable).

There are several problems here:

For a given object, there might be several interactions possible. I might want do drive the car, or access its truk, or refuel it etc.
Some interactions may require an item: I need an axe to chop down trees or a fuel source to refuel a car.
Some interactions may be non-obvious, so I need to have some sort of discovery mechanism. Some way to say to the player: "You could chop down this tree if you had an axe".
Some interactions should be very quick. Whacking an enemy with a bat should NOT require clicking and then choosing an action from menu; just clicking should work.
Added The list of objects, items and interactions is pretty open-ended. I'm still developing the game, and in the future players might make mods. This means that the interface must be generic enough to adapt to new interactions automatically.

Given these constraints, I'm really struggling to devise a good interface for interactions. I can't show a menu of all possible actions on click, because that would break (4). I can't just leave one single on-click action, because that would break (3) and probably (1).

How can I present all options to the player in a usable and preferably obvious way?


texts:
I believe everybody has heard of Minecraft. It is a deceptively simple game, that was made by a single indie developer, and sold more than 500k copies - despite having no active marketing and being technically a buggy alpha-version.

That is really great success for an indie game. And I think we can all learn much from it. So I want to examine Minecraft's game design: what, in your opinion, makes it so great? What choices work well, how they combine together to make a great game? And what design decision are bad (I don't think everything is ideal in Minecraft)

What do you think?


texts:
I actually make games only programming (SFML atm), but I was taking a look at game maker features and it looks very powerful.

What are Game Maker drawbacks? any reason why I shouldn't move into it?

It works for little games, but still it work fine with bigger projects? is it internally fast?

Thanks


texts:
GL_ONE, GL_ONE

This makes the flamingoes transparent on:

http://www.andersriggelsen.dk/glblendfunc.php

but not in cocos2d using:

sprite.blendFunc = (ccBlendFunc){GL_ONE, GL_ONE}

How can I achieve a similar effect in cocos2d?

Thank you.


texts: Getting the point of intersection from this fast ray box intersection algorithm

texts:
I have seen lots of such algorithms that return a Boolean value, but I also need to get back the intersection point and ray length.
I am looking into this example, but I'm not sure how I can extract the point of intersection from it.
I did a small experiment in JS https://jsfiddle.net/j7htk96n/ . I assumed tmin is the needed distance (or intersection point parts), but doesn't seem so.

function intersection(b, r) {
    var t1 = (b.min[0] - r.origin[0])*r.dir_inv[0];
    var t2 = (b.max[0] - r.origin[0])*r.dir_inv[0];

    var tmin = Math.min(t1, t2);
    var tmax = Math.max(t1, t2);

    console.log(tmin);

    for (var i = 1; i < 3; ++i) {
        t1 = (b.min[i] - r.origin[i])*r.dir_inv[i];
        t2 = (b.max[i] - r.origin[i])*r.dir_inv[i];

        tmin = Math.max(tmin, Math.min(t1, t2));
        tmax = Math.min(tmax, Math.max(t1, t2));
        console.log(tmin);
    }

    return tmax > Math.max(tmin, 0.0);
}

var box = {
 min: [0,0,0],
 max: [5,5,5]
};

var ray = {
 origin: [-2,-2,0],
 dir_inv: [0.66667,0.33333,0.66667]
};

console.log(intersection(box, ray));


texts: How do I debug within an animation loop?

texts:
I'm trying to see some values within an animation loop, and am naively just console.log'ing when I need to, however, this usually results in the browser crashing from all the logs.

I'm working in JavaScript, but I don't think this issue is specific to JavaScript. How do people usually debug within an animation loop to see what values are?


texts: Should the level design be in Unity scenes (GameObjects) or in 3D programs (mesh)

texts:
I am wondering what is the most common and best way to design a game in Unity from the point of view of best practice and performance and the most easily maintainable?

Is it really performant to design the level in Unity editor using a GameObject for each part of the level? or should the whole world of the level be designed in any 3D software and then exported to Unity as a on GameObject?


texts: Is setting the render target back to backbuffer supposed to take long?

texts:
I am creating a game in Monogame (XNA extension). I draw to a render target to display menu items for my game. Everything works fine, however... Whenever I set the render target back to the back buffer of my graphics device

graphicsDevice.SetRenderTarget(null);

it takes a long time (more than a second). This would be fine if I just needed my menu items at the beginning of the game. However if the game resets due to player input I have to re-initialize some of the menu items using the render target this lengthy process gets annoying.

Before I try to debug this, has anyone else experienced time delay with setting the render target back to the graphics back buffer? It works just fine when I set the render target to a created render target.

graphicsDevice.SetRenderTarget( new RenderTarget2D( device, width, height) );

That works just fine.

Edit:

I tried debugging this (C# is not my greatest language), and reached the line GL.BindFramebuffer( GLFramebuffer, this.glFramebuffer); inside ApplyRenderTargets inside GraphicDevice.cs of the Monogame Framework (Not my code).

The delay is occuring when you are trying to bind a framebuffer to a specified frame buffer target inside the OpenTK library. Debugging further requires I get OpenTK. I have to go out right now, but when I get back I'm going to test this on an XNA project (I have tested this in another monogame project with the same results) and attempt to debug further.

Edit 2:

The problem Setting the Render target back to the device back buffer after drawing to a large render target ( 8000 X 8000 ) causes the delay. I don't know the reason why I thought the buffers just swapped out.

Edit 3:

I am going to have to look into how setting render targets actually works. For now the time delay is fine, since I will have loading screens / asynchronous loading as the player progresses in the game to deal with these delays. In the end the the render target swapping the render target from a very large one causes a small delay, this seems to be expected behaviour.

Edit 4: Looking into a better solution than using a large render target.

Edit 5: Check answer


texts: How can I test shaders for nVidia on an ATi system?

texts:
I and our other devs have ATi graphics cards. However we have encountered that some shaders that compile without warnings on ATi don't compile at all on nVidia. The problems are trivial to fix, but often go unseen.

My question is, how can I make sure that my shaders will compile everywhere?


texts: XNA 3d model mesh.draw() throws TextureCoordinate0 is missing error

texts:
I've downloaded a bunch of 3d models from turbosquid.com. The majority of the one's I've downloaded are simply .fbx files. When I load the model into my game and run it, the following error is thrown in mesh.draw():

An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Graphics.dll

Additional information: The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing.

All the answers I've found online seem to tell people to reexport the model, or change something in the shader. I don't have access to these, just the fbx file. What can I do?


texts: Should the Sprites in my Boids implementation be backed by model objects?

texts:
This question is about the proper way to architect an implementation of Craig Reynolds Boids algorithm.

I have an Agent object like this:

struct Agent: Equatable
{
    let identifier = NSProcessInfo.processInfo().globallyUniqueString

    var position: CGPoint
    var velocity: CGVector

    init(position: CGPoint = .zero, velocity: CGVector = .zero)
    {
        self.position = position
        self.velocity = velocity
    }
}

And a Simulation object that holds an array of agents. Each iteration of the simulation the Simulation object updates the position and velocity of each Agent in its array of Agents. Something like this:

class Simulation
{
    private var agents: [Agent] = []

    init(agents: [Agent])
    {
        self.agents = agents
    }

    func update()
    {
        for agent in self.agents
        {
            // Update agent's position and velocity
        }
    }

This is ok. I can run the simulation and update the Agent models appropriately. However, I also want to draw the models on screen.

The question is whether I should create a new AgentView class as the view representation of an Agent model object. Or whether (1) maintaining a relationship between each Agent model and a corresponding AgentView is too cumbersome and (2) I should just replace the Agent model with AgentView entirely and let AgentView be the sole representation of an agent (sort of blending model and view state).

Thanks in advance for your help. If you would like additional clarification just let me know.


texts: Passing properties as arguments such that the resulting class can modify the original

texts:
I'm really not experienced with c# so maybe my whole methodology is wrong but here goes.
I'm trying to build a GUI that allows many many parameters to be modified in real time and have a central repository for all those variables. So I am trying to build a wrapper class around the slider so I don't have to explicitly link it to each property in the parameters class manually, and make it easier to add other generic functionalities like events or whatever.
So right now I have a UI class that holds the sliders, a slider wrapper class that holds some extra functionality, and a central parameters class. The central class shouldn't have any dependencies of the other two classes.
The UI class instantiates the slider wrapper class, and passes a Unity slider object. That part works fine.
It also passes the property from the central parameter class to which it should be linked. That's the part I'm stuck on.
UI class:
public class UIParams : MonoBehaviour
{

    private GeneralParams _centralParams;   // reference to central parameters class
    private Transform _mainUI;               // reference to main UI panel
    private Transform _panel1;               // reference to sub panel

    private MySlider _mySlider1;           // instance of my slider wrapper class
    // more sliders go here

    void Start()

    {
        //init
        _centralParams = GameObject.FindObjectOfType<GeneralParams>();
        var Panel1 = GameObject.Find("MainUI").transform.Find("Panel1");

        //sliders
        _mySlider1 = new MySlider(
            Panel1.Find("Slider1").GetComponent<Slider>(),  //pass the actual slider to the wrapper
            _centralParams.Parameter_1);                     //pass the central parameters property to the wrapper

        // more sliders go here

    }

}

Slider wrapper class:
Code (CSharp):
class MySlider
{
    private Slider _slider;                 // object to hold the slider
    private float _sliderValue;                   // value of the slider

    public MySlider(Slider Slider, float CentralParameterProperty)
    {
        _slider = Slider;                                                   // reference to Slider
        _slider.onValueChanged.AddListener(delegate { update();});      // listen for changes to slider, don't want to be checking all the time
        _sliderValue = CentralParameterProperty;                            // set slider to default value in CentralParams. How do I modify that value???
    }

    private void update()
    {
        _sliderValue = _slider.value;       // how do I change the original value from Central Params without explicitly linking each property manually?
    }
}

Central parameter class:
Code (CSharp):
public class CentralParams : MonoBehaviour
{

    public Action GeneralUpdateEvent;       // tell other classes when an update has occured

    [SerializeField]
    private float parameter_1;
    public float Parameter_1
    {
        get => parameter_1;
        set
        {
            parameter_1 = value;
            GeneralUpdate();
        }
    }

    // more parameters go here

    void GeneralUpdate()
    {
        GeneralUpdateEvent?.Invoke();
    }
}

Passing the float CentralParameterProperty into the MySlider instance works to set the default value of the slider. But obviously from that point onwards the slider only modifies the internal variable _sliderValue, not the property of the central class.
Can I set it up so I pass some object from the UI class into the MySlider on instantiation such that the MySlider instance can both get and set the values of the CentralParams property, without explicitly linking to central class within the MySlider class? Or is this just Wong?
Hope that made sense...


texts: Reduce emission of sphere object with HDRP material

texts:
I have a material which I have assigned to be used on a sphere game object which acts as stars.

This is what the settings are set to:

And this is what the Game View looks like:

I have also tried setting emission intensity to 0 nits and exposure weight to the minimum (0), but some stars still are far too bright, below is a screenshot of what it looks like with the altered emission intensity and exposure weight:

The bigger stars are far too emissive. I am trying to give each star a little glow. How do I reduce the emission?


texts: Background with small, randomly moved elements in LibGDX

texts:
I'm looking to implement a 'dynamic' background (meaning, with objects moving randomly) in my libgdx game, something similar to what you can see in this video (from the Google Play game 'Finger Dodge'):

https://www.youtube.com/watch?v=Zf8mpqf0jGc

In the above example, the background has a bunch of moving squares and triangles (and some blinks) that move randomly, independently from each other. So, what exactly should be the best approach to get something like that? I'm guessing that those background elements aren't just a bunch of single, independent textures that all get rendered at the same time with a random direction, because that would seem a bit TOO much stuff to render... Or am i wrong and that's what it might be?

So, is there any way to consistently and efficiently achieve this effect in libgdx (or if not, any other way)?

Thanks in advance!


texts: Ubuntu-Unity3D All Compiler Errors Problem

texts:
Before 2 weeks ago I can develop games on Ubuntu with Unity3D but after some updates or somethings I give "all compiler errors have to be fixed before you can enter play mode" messages. If I compile code on Intellij Rider it's ok, no problem. There is nothing on Unity console and I am researching about it since 2 weeks but I can not find any solution. I tried to install mono and .net core, yesterday find line ending problem an try to different editor but they don't work.

Produce Steps:

Create new 2D project
Add empty object to scene
Add script to empty object
Compile

ubuntu: 18.04

unity3d: 2017.4.26f1 and 2019.1


texts:
I'm working on a 2d topdown shooter, and now need to go beyond my basic rectangle bounding box collision system.

I have large levels with many different sprites, all of which are different shapes and sizes. The textures for the sprites are all square png files with transparent backgrounds, so I also need a way to only have a collision when the player walks into the coloured part of the texture, and not the transparent background.

I plan to handle collision as follows:

Check if any sprites are in range of the player
Do a rect bounding box collision test
Do an accurate collision (Where I need help)

I don't mind advanced techniques, as I want to get this right with all my requirements in mind, but I'm not sure how to approach this. What techniques or even libraries to try. I know that I will probably need to create and store some kind of shape that accurately represents each sprite minus the transparent background.

I've read that per pixel is slow, so given my large levels and number of objects I
don't think that would be suitable. I've also looked at Box2d, but haven't been able to find much documentation, or any examples of how to get it up and running with SFML.


texts: How can I stop rigidbody velocity from being overridden?

texts:
I have two behaviors on my player. "Walk" and "Dodge". Individually they work as intended by altering the players Rigidbody.velocity. However trying to dodge while holding left or right will trigger "Dodge" then "Walk" will over ride the change since you're holding left or right.

"Walk Script"
within the update loop If you press left or right

_body2D.velocity = new Vector2(speed * direction, _body2D.velocity.y);

"Dodge Script"
within the update loop If you press the dodge input it will move the player the opposite direction their facing.

_body2D.velocity = new Vector2( - (speed * direction), _body2D.velocity.y);

if you hold left or right while pressing the dodge input it will dodge in the direction you're pressing.

_body2D.velocity = new Vector2(speed * direction, _body2D.velocity.y);

I've tried changing the script execution order to prioritize the Dodge behavior over Walk. I've tried disabling the walk script during the animation with the following method.

ToggleScripts(!_animator.IsInTransition(0));

protected void ToggleScripts(bool value)
{
    foreach (var script in disabledScripts)
        script.enabled = value;
}


texts:
I've been looking at the following page, which has been very helpful: http://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html but have come into problems with the high speed turning section (about two thirds down the page)

He gives the following function to calculate the slip angle:

but it looks as if Vlat and Vlong are both vectors, and I can't see how putting vectors into the arctan function or the sgn function (which I assume is a function which returns -1 or 1 depending on the value of the sign) works.

The immediately below this he talks about F n,lat which he describes as "normalized lateral force for a given slip angle", but I am not sure how to calculate this value.

I'm not sure of any of the maths below this either, but this may be because I have not yet worked out the above bits, so if you wish to explain things below it then I would be grateful but it is not necessary.

I am writing the code using C# and XNA if this is important.

Thanks


texts: How do I resolve a collision in SAT-3D when the projection axis is zero?

texts:
I am doing SAT in 3D, right now just between cuboids/3D rects (idk the terminology). I have intersection working fully, and static collision works as long as the projection axis is not zero. But if it is zero, I am unsure how to get the minimum translation vector and overlap.
Here is the function which returns the face normals, vertices are ordered counter-clockwise starting bottom left - z for face 1, then repeat for +z, where 4 is bottom left +z:
    private float3[] GetAxesFromPoly( float3[] vertices )
    {
        float3[] axes = new float3[ 3 ];
        axes[ 0 ] = math.normalize( ( vertices[ 1 ] - vertices[ 0 ] ) );
        axes[ 1 ] = math.normalize( ( vertices[ 3 ] - vertices[ 0 ] ) );
        axes[ 2 ] = math.normalize( ( vertices[ 4 ] - vertices[ 0 ] ) );

        return axes;
    }

And here is all axes I get to test:
        float3[] axesA = GetAxesFromPoly( vertsA );
        float3[] axesB = GetAxesFromPoly( vertsB );

        float3[] allAxes = new float3[ 15 ];
        allAxes[ 0 ]  = axesA[ 0 ];
        allAxes[ 1 ]  = axesA[ 1 ];
        allAxes[ 2 ]  = axesA[ 2 ];
        allAxes[ 3 ]  = axesB[ 0 ];
        allAxes[ 4 ]  = axesB[ 1 ];
        allAxes[ 5 ]  = axesB[ 2 ];
        allAxes[ 6 ]  = math.cross( axesA[ 0 ] , axesB[ 0 ] );
        allAxes[ 7 ]  = math.cross( axesA[ 0 ] , axesB[ 1 ] );
        allAxes[ 8 ]  = math.cross( axesA[ 0 ] , axesB[ 2 ] );
        allAxes[ 9 ]  = math.cross( axesA[ 1 ] , axesB[ 0 ] );
        allAxes[ 10 ] = math.cross( axesA[ 1 ] , axesB[ 1 ] );
        allAxes[ 11 ] = math.cross( axesA[ 1 ] , axesB[ 2 ] );
        allAxes[ 12 ] = math.cross( axesA[ 2 ] , axesB[ 0 ] );
        allAxes[ 13 ] = math.cross( axesA[ 2 ] , axesB[ 1 ] );
        allAxes[ 14 ] = math.cross( axesA[ 2 ] , axesB[ 2 ] );
```


texts: Are there any file formats that support Physique and are compatible with Unity? I really don't want to start over from scratch and have to use the Skin modifier...


texts: How to move 3D Object With Touch Dragging Finger By the screen In android Unity Game

texts:
My Code is As Followed:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sphere : MonoBehaviour

{
    [SerializeField]
    private Touch touch;
    private float speedModifier;
    // Start is called before the first frame update
    void Start()
    {
        speedModifier = 0.01f;
    }

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

    {
        if (Input.touchCount > 0)
        {
            touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Moved)
            {
                transform.position = new Vector3(
                    transform.position.x + touch.deltaPosition.x * speedModifier,
                    transform.position.y,
                    transform.position.z + touch.deltaPosition.y * speedModifier);
            }
        }

    }
}

I tried with this code but object is not even responding


texts: Detecting a mouse click While in a Trigger

texts:
Why does the following code not working? (weird, sometimes it works sometimes not )
I want to move player by touching on the screen and change  the color of gameObject when detect trigger and release mouse click.
"Drag and move" script works correctly I just add following code and sometimes it works sometimes not

  private void OnTriggerStay2D(Collider2D colider)
  {

    if (Input.GetMouseButtonUp(0) & colider != null)
    {
      colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;

    }

  }

There is a full script :

  private Camera _cam;
  private Vector3 _daragOfset;
  [SerializeField] private float _speed = 4.55f;
  private bool isEntered = false;

  void Update()
  {
    if (Input.GetMouseButtonDown(0))
    {
      _daragOfset = transform.position - GetMousePos();
    }
  }

  private void OnTriggerStay2D(Collider2D colider)
  {
    if (Input.GetMouseButtonUp(0) & colider != null)
    {
      colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;
    }
  }

  void Awake()
  {
    _cam = Camera.main;
  }

  void OnMouseDrag()
  {
    transform.position = Vector3.MoveTowards(transform.position, GetMousePos() + _daragOfset,_speed * Time.deltaTime);
  }

  Vector3 GetMousePos()
  {
    var mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
    mousePos.z = 0;
    return mousePos;
  }


texts:
What is the MTV (Minimum Translation Vector) in SAT (Seperation of axis)? and how can i use it?

Im trying to create my first game, where a ball can hit a a static brick (rectangle). Now if a ball collides with a brick, then i need to figure out which side the ball collided with so i can tell the ball which direction it should bounce off to.

For example, if a ball is heading nortwest and hitting the brick on its right side, then it should bounce in a northeast direction.

however if the ball hit's the bottom side of the brick, then the ball should be heading southwest.

So can the MTV be used in this situation? can MTV tell me which side of a rectangle the ball has impacted?

Please note i have implemented SAT in my game, and the collision detection works fine, my question now is, can i use MTV to actually handle a collision response?

Any help is appreciated.


texts: Is it possible to achieve a smooth sprite animation with a fixed 60 FPS using Java 2D?

texts:
I've seen a lot of different game loops, and before implementing anything complicated I decided to start with a capped 60 FPS. My run method looks like this in my game thread:

/**
 * Fixed Frames Per Second = 60
 */
public void run() {
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            stage.render();
        }
    }, 0, 17);
}

The stage is a canvas, and the render method looks like this:

public void render() {

    BufferStrategy bufferedStrategy = this.getBufferStrategy();

    if (bufferedStrategy == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics2D graphics2d = (Graphics2D) bufferedStrategy.getDrawGraphics();

    for (Actor actor : actors) {
        graphics2d.setColor(Color.WHITE);
        graphics2d.fillRect(0, 0, 600, 600);
        graphics2d.drawImage(actor.getDrawableImage(), actor.getX(), actor.getY(), 32, 32, this);
    }

    graphics2d.dispose();
    bufferedStrategy.show();
    Toolkit.getDefaultToolkit().sync();
}

The only "actor" sprite is 32x32, is currently moving 1 pixel at a time, and is too slow. So I bumped it to move anywhere from 2-4 pixels at a time across the stage, but now it is chunky. Is this related to my implementation or specific to Java 2D? The movement happens while the user presses one of the arrow keys.


texts: Render to Texture2DArray slices in DirectX11?

texts:
I would like to set a slice of a Texture2DArray as a render target in D3D/DirectX11. It's not clear how to do this.

What I'm looking for is the DirectX equivalent of glFramebufferTextureLayer(), which sets a slice of a GL_TEXTURE_2D_ARRAY_EXT as a texture resource of a Framebuffer Object.

In D3D11, you set a render target using ID3D11DeviceContext::OMSetRenderTargets, and you can set a Texture2DArray resource view as a render target. However, the only way I see to select which slice of the texture is painted is to use the SV_RenderTargetArrayIndex semantic in an HLSL geometry shader. (The semantic is only available in a geometry shader).

My pipline doesn't have a geometry shader, and I don't know at compile time which primitive type I will be rendering - I'm reading models out of input files. It seems like, to add a passthrough geometry shader I would need one shader program for every possible primitive type (terrible).

The desired output slice will not change between rendering passes. Is there no way to set a slice of a Texture2DArray as a render target without using a geometry shader?


texts: Unity Json utility does not serialize DateTime

texts:
Like the title said the unity json utility does not seem to allow me to serialize the DateTime structure. Just to clarify the problem is that I'm serializing this class:

[Serializable]
public class SaveData {

public Vector3 playerPosition;
public Quaternion playerRot;
public List<Item> inventory;

public DateTime saveTime;

public int playerHealth;

public int strength;
public int attack;
public int defense;
public int agility;

}

When I actually write to the json file I get everything but the DateTime and no errors. This is the result:

{
"playerPosition": {
    "x": -142.27000427246095,
    "y": -7.000000476837158,
    "z": -112.80999755859375
},
"playerRot": {
    "x": 0.0,
    "y": 0.0,
    "z": 0.0,
    "w": 1.0
},
"inventory": [],
"playerHealth": 100,
"strength": 0,
"attack": 0,
"defense": 0,
"agility": 0
}

Is there a way around this?

A little update to this question so that I can show another way I've worked around this problem if the answer below isn't for you.

I was recently working on a similar problem and solved it by doing the follow:

I created a new class called "NewDateTime":

[System.Serializable]
public class NewDateTime {
public int second;
public int minute;
public int hour;

public int day;
public int month;
public int year;

public NewDateTime CreateNewDateTime(DateTime dateTime) {
    NewDateTime newDateTime = new NewDateTime();
    newDateTime.second = dateTime.Second;
    newDateTime.minute = dateTime.Minute;
    newDateTime.hour = dateTime.Hour;
    newDateTime.day = dateTime.Day;
    newDateTime.month = dateTime.Month;
    newDateTime.year = dateTime.Year;

    return newDateTime;
}

public override string ToString() {
    return day + "/" + month + "/" + year + " at " + hour + ":" + minute + ":" + second;
}}

and then for example when I want to save the date to json I would do something like the following:

saveDateTime = newDateTime.CreateNewDateTime(DateTime.Now)

it's a rather simple workaround but I thought it might help.


texts: How to create a LUT from original and processed images (not perfectly the same)?

texts:
I would like to create a certain LUT for my game in Unity.
The usual way would be to take a screenshot in your game, process this screenshot in an image editor like Photoshop / GIMP and then calculate the LUT from that.

I would like to re-create the LUT used in the movie Memories of Murder.

I do not have access to the un-processed film material, so I can not automatically create the LUT as I would normally do with the above approach.

The closest comparison between the original colors and the processed version that I could get were these images:

Is there any way to create a LUT from these 2 images somehow even if they don't show exactely the same moment?


texts: Creating models in 3ds max and exporting as .x for XNA

texts:
I have created a few models in 3DS max which contains textures, geometry and animations . .however .fbx doesnt really support textures.. So im planning to use .x format.. I have seen a few converters in pandasoft but once i unzip the file and place the .dle file in the plugins folder of 3D max gives an error saying failed to initialize..
Is there any way to convert my .max models into .x format ? ? I dont know blender so that isnt an option. . I'm currently using 3ds max 2013

After adding the .3DS object content importer. . i get the following error:

.3Ds files along with the solution


texts: Unreal Engine 4 - AI MoveTo always fails

texts:
I try to move a character with AI MoveTo, but it always fails. I tried to do this with standart ThirdPersonController and a custom one. The blueprint is simple

When the event happens, it starts printing "failed". I checked many times if I have a NavMesh on the level or any other problems with it, but I don't think there are any problems with that. Any ideas?


texts: Python/PyGame mixer.music playback of OGG file has intermittent clicking sound - how to proceed?

texts:
I have a class within my python + pygame game that handles sound - it worked well until I tried use pygame.mixer.music to switch between streaming .ogg music files. The class switches between them on the pause event.

The issue I'm having is that the music will play, and even switch between tracks fine, but about half the time I'm getting a quiet, regular clicking noise over the sound track. I've checked, and the pygame mixer is set to the same bitrate as my .ogg files. I've tried playing with number of channels and tracks, all to no avail. I'm not sure what the root cause of the clicking is - whether I've chosen a poor file encoding / bitrate, or just not initialized/called pygame mixer correctly.

Here is the problimatic code:

class SoundMgr():

def __init__(self):
       pygame.mixer.init(22050, -8, 4, 4096)
       self.musicFilename = ""
       self.musicPos = 0
       self.musicVolume = .35
       self.musicMuteVolume = .1

def playMusicTrack(self, which):
    pygame.mixer.music.load("data/music/" + which + ".ogg")
    pygame.mixer.music.set_volume(self.musicVolume)
    pygame.mixer.music.play(-1)
    self.musicFilename = which

def dampenMusic(self):
    mark = pygame.mixer.music.get_pos() * 0.001
    self.musicPos += mark
    pygame.mixer.music.load("data/music/" + self.musicFilename + "b.ogg")
    pygame.mixer.music.play(-1, self.musicPos)
    pygame.mixer.music.set_volume(self.musicMuteVolume)

def undampenMusic(self):
    mark = pygame.mixer.music.get_pos() * 0.001
    self.musicPos += mark
    pygame.mixer.music.load("data/music/" + self.musicFilename + ".ogg")
    pygame.mixer.music.play(-1, self.musicPos)
    pygame.mixer.music.set_volume(self.musicVolume)        </code>

When I call dampenMusic / undampenMusic the track plays correctly, but about half the time it has a clicking sound over it. The other half of the time it plays perfectly. I've tested, and I can't discover any pattern to when it will / won't have the static.

The clicking noise is about 2 times a second, and is about 50% the volume of the track.

Anyone who is more experienced with pygame / sound encoding able to give me any tips?


texts:
I have a hero that can aim his gun.
When the user aims down, I play the animation "gun_aim_lo".
When the user aims up, I play the animation "gun_aim_hi".
I do this via a BlendTree.

The "BlendVal" is set by the current mouse position.
float f = Input.mousePosition.y / Screen.height;
_animator.SetFloat("BlendVal", f);

This works fine.
When the user then presses the fire button, the hero shoots his gun.
I play the gun_shoot animation using a Triggger like that:
_animator.SetTrigger("PistolShootTrigger");

However, I have now noticed that I need different gun_shoot animations, just like for the aiming:
I need a gun_shoot_hi and a gun_shoot_lo animation according to the aiming position, else it would look strange if the user for example aims low and then the shoot-straight-animation is being played.
I would need to be able to blend between them according to where the user aims when he shoots.
Can I combine a BlendTree with a trigger?
I think I can only trigger single animations, and not a blend tree.
Can somebody tell me how my idea could be achieved?


texts: In GM Studio, how do I prompt the player for a password?

texts:
I could make strings in earlier Game maker versions, but it doesn't work in the Studio version when I try.  The code I used:

When Left Mouse Clicked on Password Bar:

var str;
str=get_string("Crack the code!","");
if str!="pswrd" && str!="PSWRD"
{
    check_answer=false;
    room_restart()
}
else
{
    check_answer=true;
    room_goto_next()
}

I want a box to pop up saying "Enter Password".  Then to enter the password, and if correct, go to a room, for example.  I am using physics in Gamemaker Studio 1.4.


texts: How to draw a NavMesh Path to a destination without traversing the path in Unity3d?

texts: I have a set of pre-determined destinations. When the user chooses any one of those destinations, the path to the destination should be drawn, similiar to google maps. I am trying to do this in unity, but not able to figure out just how.


texts: How can I scale/zoom to a point in canvas in the game?

texts: I am using html5 canvas to build a MMO game. When I scale my background by default it scales to (0, 0) which is the top left corner of the background. If I have other sprites on the screen they all will look like they are shifting to the bottom right a little bit. Suppose my sprite(player) is at (x,y) of the map and it is placed center on the canvas.How can I make the background scale or zoom to (x,y) instead of (0,0)? Its world position is (x,y) but its screen position is always (canvas.width / 2, canvas.height / 2). I think in this way the sprites around my player wouldn't shift their position to unexpected places. But I don't know how to do this.


texts:
Game development is currently a largely non-academic enterprise.  There are a lot of commercial developers of games, as well as a large hobbyist community.  The academic community focusing on games seems to be small, and new.  [Or so it appears to me].

Having said all that, are there some must read papers/books on game development from academics?


texts: How to move an object from off screen right to left continuously?

texts:
I am trying to make an object move from off screen on the right to off screen left and continuously generate (like the flappy bird pipes). How would I do this with my current code below? I have tried creating a class like I did with the "ball" class but I can't seem to get it to work... Any examples or help would be appreciated. (I am very inexperienced in game development and java so please bear with me). This is my current code, I have the ball that jumps in the air and now want to make the spike move from off screen right to off screen left and generate another "spike" each time. I have drawn the spike which at the moment is just a texture that does not do anything. Thanks.

class Ball {

public static final float GRAVITY = -500;
public static final float BOUNCE_DAMPENING = 0.0f;

public final Vector2 position = new Vector2();
public final Vector2 velocity = new Vector2();
public final Vector2 acceleration = new Vector2(0, GRAVITY);

public void update (){

 float deltaTime = Gdx.graphics.getDeltaTime();
    velocity.add(acceleration.x * deltaTime, acceleration.y * deltaTime);
    position.add(velocity.x * deltaTime, velocity.y * deltaTime);

    if (position.y <0){
        position.y = -position.y * BOUNCE_DAMPENING;
        velocity.y = -velocity.y * BOUNCE_DAMPENING;
    }
}
}

public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture ballTexture;
Ball ball;
Texture spikeTexture;

@Override
public void create () {
    batch = new SpriteBatch();
    background = new Texture("gamebackground.png");

    ballTexture = new Texture("ball2.png");
    ballTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);

    ball = new Ball();

    spikeTexture = new Texture("spike2.png");

}

@Override
public void render () {

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (Gdx.input.justTouched())
            ball.velocity.y += 350;
        ball.update();

    batch.begin();
        float scaleFactor = 2.0f;
        batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.draw(ballTexture, ball.position.x, ball.position.y, ballTexture.getWidth() * scaleFactor, ballTexture.getHeight() * scaleFactor);

        batch.draw(spikeTexture, 80,-260, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);

        batch.end();

}

@Override
public void dispose () {

    batch.dispose();
    background.dispose();
    ballTexture.dispose();

}

}


texts: Transform existing C++ OpenGL project from glut/glew to GLFW

texts: Is it possible to easly transform existing glut/glew to GLFW API?


texts:
I'm using OpenGL via GLUT in Ubuntu.

While writing text in a text editor, the first keystroke is printed immediately.
But if we keep pressing the key, it waits for a moment and then prints a trail of that character.

This is to reduce the sensitivity while typing.

With GLUT, function callbacks for keyboard behave like that.

glutKeyboardFunc( keyboard );
glutKeyboardUpFunc( keyboard_up );

Now if we keep pressing a key, there is a considerable delay between the first and the second call of keyboard ( and keyboard_up) function. But in real gaming, this not should be the case.

Question 1: How to solve the problem?

Question 2: keyboard_up gets called even if I press and hold a key. Why so? I think it is supposed to get called only when I release it. Moreover, this also suffers from the above jerk problem.

Question 3: For glutMouseFunc( mouse ), the mouse function gets called whenever we press or release a mouse button. I want this too to get called repeatedly if I press and hold my mouse button, and that too without jerk. How to do so?


texts: Computing a full revolution for an arbitrary orbit?

texts:
I'm making a game in which the goal is to get as many planets as possible to orbit around a star.  The user launches planets at any distance away from the sun (as long as it's on-screen), and in any direction (possibly even directly at the sun, though their game won't last very long).

This means orbits can be circular, elliptical, or--more than likely--irregular, something like this:

(Image originally from here)

The rules for my game that the player may launch planets as frequently as s/he likes...but they will only score a point for their first revolution (so spamming planets isn't likely to score very much).

Right now, the gravitational force is just F = ma (i.e. a constant force towards the sun).  I'm trying to figure out when a planet in arbitrary orbit has completed a full revolution.  This is how I'm doing it currently...

// If this planet is active...
Vector2 a = _body.position.normalized;
Vector2 b = (a + _body.velocity).normalized;

float angle = Vector2.Angle (a, b);
this._total_angle += angle * Time.deltaTime;

if (this._total_angle >= 360) {
    // If this planet has made a revolution...
    ++this._revolutions;
    this._total_angle = 0;
    this.OnRevolution.Invoke (this);
}

However, this is incorrect for anything besides circular orbits.  No good.

Given all of this (and my near-total unfamiliarity with orbital mechanics), how can I tell when a planet in an arbitrary orbit has completed one full revolution?

EDIT: No, the planets will not affect each other's orbits (though they can collide into one another, but they'll just explode).


texts: Good examples of 'transferable game logic' across genres?

texts: Do any of you have any good examples from two or more games that share some of the same game logic, but are of entirely different genres? Could very well be one of your own games. Take Warcraft 3 and World of Warcraft for instance. Entirely different games, but they could have some game logic in common without us knowing.


texts: Is there an alternative to SDL 1.3 for a C++ game that should run on iOS and Android?

texts:
I've used SDL for many desktop games, always as the cross-platform glue for:

Creating a window
Processing input
Rendering images
Rendering fonts
Playing sounds/music

It has never disappointed me at those tasks.

But when it comes to graphics, I prefer to work with the OpenGL API directly, even though all of our games are 2D.

In the project I'm currently working on, I've made sure to only use the API subset supported by both OpenGL 1.3 and OpenGL 1.0, so making the thing run on Android should be easy, I thought.

Turns out there is no official Android or iOS port of SDL yet. However, there's one in SDL 1.3, which is still in development.

SDL 1.3 doesn't seem very appealing to me for three reasons:

It's been in development for at least 4 years, and I have no idea when it will be done, not to mention stable.
It's not ported to as many platforms as SDL 1.2.
From what I've seen, it uses OpenGL for drawing, so I suppose the community will move away from directly using OpenGL.

So I'm wondering if I should use a different library for our current project - it doesn't matter much if I need to port my existing code from SDL 1.2 to SDL 1.3 or to some other library. We're planning to release on Windows, Mac OS X, Linux, iOS and Android, so good support for these platforms is essential.

Is there anything stable that does what I want?


texts: How to handle interaction with the map in a 2D-RPG-typed TileMap?

texts:
Sorry if this is a long post, but I'd like to explain the context before asking my question ^^"

I'm currently working on my "first" game (the more advance one, at least). It'll be a 2D-ARPG where the player will be able to interact with the map, by doing things like chopping tree, farming, mining, etc...

As it is my first game, I didn't really know where to go so I started by implementing basics functionalities, and i added more while the game took shape.

With that in mind, the first thing I did is implementing a TileMapReader that take JSON files generated by Tiled, and render it on screen. I've kept the structure Tiled use (github.com/bjorn/tiled/wiki/JSON-Map-Format) in order to store the tiles : The Map have a list of Layer, and each Layer as a list of "gid", corresponding to a Tile in the Tile Set. I generate my map directly from the Tile Set, without creating a Tile Object ... So my map really is just a bunch of Integers, corresponding to a Tile id. I generate then the display by pasting the right piece of the Tile Set at the right place on the map.

After that, I start implementing a Camera that could be move around the Map, and then a Player character who can move around too. Currently, the player is an instance of a "Body" class that is store with a x;y location in a field on the Map Object, and is display on a specific empty Layer like any other Tiles (except the sprites come from other external pictures, and not the Tile Set). I linked the control and the Camera to the character, and here I go ! Walking-in-forest simulator 2016 !

So now, I want to start implementing interaction like collision and so. The problem is that I really can't decide how to do this.
The two first thing I'd like to add to the game are interactions with the trees : collisions and chopping.

Since the beginning, trees are just collections of tiles on different Layers, like the rest of the map. But I think I have to make them as Object entity, just like my "Body" ...

To do so, I've thought of servals ways :

I could parse my Map Tile by Tile, and store my tree-tile's position in order to create my tree, but I find it way to difficult since I don't really know wish Tiles in the Tile Set are the tree-tiles, so I don't know theirs gid. Moreover, a tree is composed of servals Tiles, placed on servals Layers. So it'll be a pain to locate a single tree correctly on the map. Finally, the problems multiplies themselves if I add other entity like water or rocks ...
Another idea was to create another Map in which I store all the entity as Objects (and use the tile map for ground and water only). But if I do that, would the Tile Map really be useful ? wouldn't it be better to just randomly-generate a Map entity-full directly ? And since I want to add farming in the future, grass tiles would be passed on the Object-Map too, right ? So the Tile Map will become completely obsolete ...

I decided to go with the second one, but here again, I had to pick a way to store this second Map.
I wanted to go with a Tree-like Graph in which I would separate different sections of the map (like each node is 1/2 of it's parent node, and the last Nodes are the different entity with their positions). That would help a lot for the collision's detection, but I think it still really complicate to implement ...

So here my questions : is my approach on this player-world interactions correct ? since it is my first "big" game, I really would like to know if I'm doing it right or not ... and if not, how can I handle this interactions properly ?

I'm posting these here, hopping that there is a simple answer to it (even "just do it" would do ^^ (even if some explanation would be really nice)) and that this post will not be be closed for being too broad ^^"


texts: Unity Input System: Rebinding composite parts

texts:
I have controls for movement defined as composite Binding through Vector 2D.

I have shown in settings any single binding which is not composite. I understood that I must get a composite index for binding, which is correct, I got the right binding like up, down, ...
But whenever I click on button for change something on Move, whole game freezes. And I can't do anything... Is there something I'm missing, when rebending part of composite?
Here is my code and screen, how the control settings looks.
public void Start()
{
    Button.onClick.AddListener(() =>
    {
        Key.Text = "Listening";

        _operation = Action.PerformInteractiveRebinding()
            .WithTargetBinding(BindingIndex)
            .Start();

        _operation.OnApplyBinding((op, path) =>
        {
            Action.ApplyBindingOverride(BindingIndex, path);
            Key.Text = Action.bindings[BindingIndex].ToDisplayString();
            _operation.Dispose();
        });
    });
}


texts:
At the moment I have not worked with android and am not familiar with its capabilities.
In the browser, it is possible to get an image from the canvas using the methods
toDataURL()
toBlob()

Are there any similar methods on android canvas (android.graphics.Canvas, if I understood correctly) to get an image?
Or is it possible only in canvas in the webview component?
Thanks.


texts: Can Harlowe for Twine 2 handle variable references inside a Datamap?

texts:
I'm starting to learn Twine and I'm putting together a little framework for making a game.

I'm trying to make a DataMap named 'Door' that has a key/value pair of "openCondition",$doorUnlocked. What currently happens is that "openCondition" is set to what $doorUnlocked is when 'Door' is created (false).  This is fine, but when $doorUnlocked becomes 'true', "openCondition" stays the same, because it's already been set.

Is is possible to set a DataMap value to a reference of a variable?
Are reference variables even built into Harlowe?
If not, are they available in any other Twine format?


texts: differing methods of Instantiating GameObjects in Unity (what is the difference?)

texts:
I have been using Unity a while and always Instantiated objects slightly differently from what many of the tutorials and posts online say (I've seen 3 very similar ways). It seems to have the same outcome much of the time, however now I am trying to instantiate the prefab using my "Resources" folder instead of dragging it from the inspector and on one method it said it was an 'object' not 'gameobject'.
I can't really find anything on Unity website or here, so what is the difference between the following:

 // These two lines to me seem identical, but most tutorials dont cast, and rather use the latter of the two instead, why?
 currentBall = (GameObject)Instantiate(Resources.Load(prefabName, typeof(GameObject)));
 currentBall = Instantiate(Resources.Load(prefabName, typeof(GameObject))) as GameObject;

  // This one I know is different somehow, because Unity said cannot convert from Object to GameObject, but honestly i do not understand why
  currentBall = GameObject.Instantiate(Resources.Load(prefabName, typeof(GameObject)));


texts:
I have a "board" with a ball (rigidbody) moving over it and colliding with obstacles.

I want its velocity magnitude to remain constant throughout time.

How do I achieve this?

What I've tried/achieved so far:

My first guess was to use OnCollisionExit to set the velocity manually, but that lead to weird physics.
I don't see how to use AddForce to do this since the previous movement would still be factored.
To be clear, what i want is to set the velocity at all times to rigidbody.velocity.normalized x magnitude, where magnitude is a float I set previously. This would allow the physics engine to make all impact math to decide the direction of the ball after the collision, but my math would keep the velocity intact.
I then decided to add UpdatedFixed and on every call set the velocity as stated above. It's working, but feels like a bad hack because I'm updating the velocity every frame and forsaking the physics engine.


texts: How to solve artifacts caused by vertex lighting in my voxel engine?

texts:
My current lighting system bakes the light amount based on ray-tracing from the light source to the 8 corners of the block (so per-vertex) and the distance to the light on the blocks. It works acceptable, but it's definitely not perfect.

Of course the blocks are made out of faces, which are made out of triangles. In the situation shown in the screenshot, where there is a light directly behind the camera, you get those weird triangle lighting issues.

How can I fix this problem?


texts: How can you create a trigger collider between two moving objects?

texts:
I want to create a trigger-collider between two boxes. When one of the boxes moves, the trigger is supposed to change its size and shape so that its left and right edge stay attached to the two boxes.

How can I implement this in C# or JavaScript?


texts: Skewed 3d model when moving device around with Unity and Vuforia

texts:
I am having trouble with the orientation of a 3d model that is larger (think queen-sized bed) than the target image(a4 size bond paper). The model appears to be slanted in a way that looks totally unrealistic especially when moving the device around. Is there a way to keep the model horizontally aligned with the real-world floor?

I have already enabled Extended Tracking but the behavior is still present. I have also set the world center to Specific Target and set Device Camera focus mode to FOCUS_MODE_CONTINUOUSAUTO.

Thank you.


texts: Shortest path from BitmapSource to DX11 Texture2D

texts: Does anyone know a way to get from (WPF) System.Windows.Media.Imaging.BitmapSource to a DX11 Texture2D without going to System.Drawing.Bitmap? I'm trying to strip out all System.Drawing references as this code it for WPF only.


texts: Good recent examples of educational games?

texts:
I'm looking to make an educational game. I know they have a horrible reputation, but I still think there's a future for them. Unfortunately, it seems to me like most educational games were in the 90s. Does anyone know of any recent, semi-decent educational games?
I'm specifically interested in teaching a subject (ie, Chemistry) rather than a skill (ie, typing).
I know there was this question: How do I make educational games engaging not boring?
But it was over 5 years ago.


texts: Shall we create our game engine in this case?

texts:
Although my friend and I are not interested in game development, we like creating tools. We would really like to give life to our own game engine, however, we don't want to put effort into something useless. Develop something what can be used by smaller or "medium-sized" companies. It's not about the most modern graphics and technologies. Something like WoW's engine 10 years ago or GTA III's would be a dream.

So, is it possible that 2 (assuming) experienced programmers can create something like that?


texts: Find grid cells in 2D grid based on object size and rotation

texts:
I am working on a game that uses a grid system that allows the player to place buildings in the world. Each cell in the grid is 64x64. All buildings will be a multiple of 64x64, so everything will evenly fit in the the grid.

Below shows an example of a building that is 128x64 and placed at grid position 64x64. The client sends the server the "base" cell, which in this case is 1,1 (@64x64), and knows the building that is being build is 128x64 so it sets both cells to the "occupied" state which means a building is placed in those 2 grids.

The problem I am having is allowing the client to rotate the building either 90, 180, or 270 degrees.

For example, if the client wanted to place the same building, but rotated 90 degrees, it would look like this:

Basically what I am asking is: Given the client sends to server the location to build 64x64, and sends 90 for the rotation, how can I (on the server) figure out which cells are going to be build on?

Currently I am using this code to get the grids, but it doesn't allow for rotation since I have no idea.

https://pastebin.com/UaaUa7jZ

Any help would be appreciated.


texts: Error in the order of the target points to be followed. How to set the order of elements in an array?

texts:
I have a project where it has 1 NPC and 3 target points:

In the project I set the NPC to go to target point 1, then to 2, then to 3.

Expected path:

Path that is occurring:

This problem did not happen out of nowhere, but first I will explain the creation of the target points.

I created the first target point, added the components it needed, and then replicated it. Selecting the first target point and pressing CONTROL + W. I positioned the second target point, and then, again selecting the first target point, I again replicated it.

The order of the path was as expected. I modified some code (none of the codes I modified related to the NPC or target points). After that I created a new target point (replicating it from the first target point) and then my problem started.

The NPC was initially going to target point 3, to the 4, 1 and then 2.

Even excluding target point 4, the order did not return to the expected (1, 2 and 3).

I inserted a print after the loop that causes the NPC to move toward the target points, so I could figure out the order of the target points, and it is making sense with the order of the path that is taking place.

Blueprint + Print:

3 to 1 to 2.

I created 2 more target points, and see how the order changes without any sense:

4 to 5 to 1 to 2 to 3.

I added another 1 target point to see if it meets a pattern:

No sense at all.

I'd like to know how to set the order of target points in the array.

EDIT 1 (Root of the problem)

From what I researched, I came to the conclusion that the problem is due to the function Get All Actors Of Class (that I use to make the NPC follow the target point):

It was also researching that I discovered that I can search for a specific actor using tags.

Link where I made the discovery:

https://docs.unrealengine.com/en-us/Gameplay/HowTo/FindingActors/Blueprints

But this feature does not serve me, because I do not want to establish an exact number of target points, I would like the order of the path to be given by the name of the target points or at least by the creation order.

EDIT 2 (today opening the project again, the order is correct)

Correct order:

I suspected that if I added new target points, the problem would come back, but that was not what happened.

Again the order is correct:

Even so, I'd like you to tell me if there is any way to know all the elements of an array, and thus be able to treat, set, and order them. For this problem may occur again at some crucial moment.


texts: When should new threads be created in a game or how should time consuming task be handled?

texts:
This has been a question that has always troubled me while thinking about the code and logic behind gaming, I was wondering when and when not, is it appropriate to create new threads for different tasks or how should I handle long tasks that could potentially freeze my game?

The first situation I could think of would be the rendering and the update loop. My thought behind this is that keeping these two seperate would prevent update problems because of a low frame-rate so even if the frame rate is changed there would still be a consistent update cycle.

The second situation is somewhat more specific and is just an example but say my game has multiple building components that can be placed over the world and my game updates them every second or so to check maybe if they are floating (if they have physics) or maybe if it's environment has changed, should this update cycle also be in another thread because it could take a long time?

How about if I was pinging a client, would my server not freeze whilst waiting for a response? Is this another situation where threads should be created? or is there another technique that I should be using to enhance performance and efficiancy?


texts: how can I put an array of objects into a script?

texts:
I want to create an animation from an object sequence. I already achieved exactly what I needed with the "MeshAnimaton script" from bummzack:

using UnityEngine;
using System.Collections;

/**
 * Animate a mesh by cycling through different meshes.
 * @author bummzack
 */
public class MeshAnimation : MonoBehaviour {

    public Mesh[] Meshes;
    public bool Loop;
    public float FrameDuration;

    private int _index;
    private bool _playing;
    private float _accumulator;
    private MeshFilter _meshFilter;

    public void Start()
    {
        _meshFilter = GetComponent<MeshFilter>();
        _index = 0;
    }

    public void Update()
    {
        if(!_playing){
            return;
        }

        _accumulator += Time.deltaTime;

        if(_accumulator >= FrameDuration){
            _accumulator -= FrameDuration;
            _index = (_index + 1) % Meshes.Length;

            if(_index == 0 && !Loop){
                Stop();
                return;
            }

            _meshFilter.mesh = Meshes[_index];
        }
    }

    // play the animation
    public void Play()
    {
        _playing = true;
    }

    // stop the animation
    public void Stop()
    {
        _playing = false;
    }

    // restore the first frame
    public void Reset()
    {
        _index = 0;
        _accumulator = 0.0f;
        _meshFilter.mesh = Meshes[_index];
    }

    // Mouse down to toggle Stop/Play, just for testing
    public void OnMouseDown()
    {
        if(_playing){
            Stop();
            Reset();
        } else {
            Play();
        }
    }
}

That worked fine with an object sequence which consisted of 20 meshes. But now I have to do the same with sequences that consist of big amounts of objects. Is there a way to put an array of certain object names into the script instead of dragging each mesh file separately onto the script component? I would appreciate any kind of help.


texts: I have a buffer of about 134 million particles and a very powerful computer to render them smoothly, but I am getting an error when trying to render them as primitive lines. It says that I cannot render more than around 1 million. Is there a way I can do this? Is there a better way to render this other than with lines? I'm comfortable with having 1 pixel points or anything as long as the vertices are shown all the time. I'm basically just plotting the points.


texts: How to make the snake to pass from one side of the screen and come out the opposite side?

texts:
How do I code the left and right collision, and also tell me how I can set the collision of snake according to the form size.

If i want to change or maximize the form, snake should collide with the ending boundaries of the form ..


texts: Direction from the camera to the light source

texts:
I'm currently writing a game using OpenGL and GLSL. For the shader I need the direction from the current camera to the light source. The lightsource is given by lightSource.position as a uniform as well as the ModelviewMatrix (mat4).

The task is

  TODO: compute the vectors from the current vertex towards the camera and towards the light source

I need to fill two varyings with those information, but I'm not sure how to compute them.
In addition I've the following information:

#version 330
layout(location = 0) in vec3 vertex;
layout(location = 1) in vec3 vertex_normal;


texts:
LibGdx sprite rotation vs Box2D physics rotation problem

Tearing my hair out on this one. I am an experienced software developer, but very new to LibGdx and Box2D development.

I am writing a game where the game board is the size of the screen. The game board does not pan - it just fills the screen. For the descriptions below presume that the device is being held vertically, so that vertical is the longest length. Also, for the description below, presume that on a device with a 'normal' aspect ratio, circles will be rendered perfectly circular, but a device that is narrower than expected, the circles will be squashed so that they are taller than wide.

I have a number of circle shapes that are rendered to the screen.

Because different devices will have different width / height aspect ratios, I am happy for the circle shapes to be squashed on a device that is narrower on the horizontal than expected (I am trying to avoid maintaining identical aspect ratios and forcing black borders at the edges of the game board).

My problem is this: when Box2D debug renders the screen, showing the physics objects, the circle shapes maintain their width and height, even when rotated. To describe further, if a sphere is displayed with 0 degree rotation on a narrow device, it takes an oval shape that is taller than it is wide, as would be expected on a narrower than expected device. If you rotate the circle shape by 90 degrees, the Box2d debug renderer shows the rotation (there is a line that sticks out of the centre of the object at an angle that shows the angle of rotation) but the object maintains its taller than wide oval shape. This is correct, as a sphere on a horizontally narrower aspect-ratioed device will always be displayed taller than wide.

When I attempt to overlay a LibGDX sprite on top of the Box2D physics simulation (the sprite, in its unaltered form, is circular, and is then scaled to the devices aspect ratio), with a zero degree angle, it appears nicely mapped to the Box2D representation - taller than it is wide. However, when I rotate the LibGDX sprite by 90 degrees, it appears rotated the way a billboard image would be rotated, so it is now wider than it is tall (imagine drawing a taller-than-wide oval on a piece of paper and turning the piece of paper by 90 degrees).

It appears to me that Box2D applies rotation before it applies the camera scaling - so the circular object is rotated first (maintaining its circular shape under the hood), and then sqaushed to form an ellipse that is taller than wide on the screen. Whereas, the LibGDX engine applies the transforms in reverse. The object is squashed to taller-than-wide, then rotated, so it becomes wider-than-tall on the screen.

I have pasted the relevant code below:

//screen size in box2D metres
private static float screenHeight = 100.0f;
private static float screenWidth = 70.0f;

//set up the camera in the show() method
    cam = new OrthographicCamera(screenWidth, screenHeight);
    cam.position.set(screenWidth / 2, screenHeight / 2, 0);

//render method
batch.begin();
for (int i = 0; i < ballList.length; i++)
{
    ballList[i].render(batch);
}
batch.end();

//ball class render method
public void render(SpriteBatch batch)
{
    ballHappyImage.setOrigin(64.0f, 64.0f);
    ballHappyImage.setPosition(body.getPosition().x - 64.0f, body.getPosition().y - 64.0f);
    float scaleWidth = Gdx.graphics.getWidth() / 1400.0f; //hardcoded to make things fit correctly
    float scaleHeight = Gdx.graphics.getHeight() / 2000.0f; //hardcoded to make things fit correctly
    ballHappyImage.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
    ballHappyImage.setScale(scaleWidth, scaleHeight);
    ballHappyImage.draw(batch);
}

The images below show the Box2D debug rendered line drawings overlayed on the libgdx sprites.


texts: Velocity control of the player, why doesn't this work?

texts:
I have the following code inside a while True loop:

if abs(playerx) < MAXSPEED:
    if moveLeft:
        playerx -= 1
    if moveRight:
        playerx += 1

if abs(playery) < MAXSPEED:
    if moveDown:
        playery += 1
    if moveUp:
        playery -= 1

if moveLeft == False and abs(playerx) > 0:
    playerx += 1
if moveRight == False and abs(playerx) > 0:
    playerx -= 1
if moveUp == False and abs(playery) > 0:
    playery += 1
if moveDown == False and abs(playery) > 0:
    playery -= 1

player.x += playerx
player.y += playery

if player.left < 0 or player.right > 1000:
    player.x -= playerx
if player.top < 0 or player.bottom > 600:
    player.y -= playery

The intended result is that while an arrow key is pressed, playerx or playery increments by one at every iteration until it reaches MAXSPEED and stays at MAXSPEED. And that when the player stops pressing that arrow key, his speed decreases until it reaches 0.

To me, this code explicitly says that...

But what actually happens is that playerx or playery keeps incrementing regardless of MAXSPEED and continues moving even after the player stops pressing the arrow key.

I keep rereading but I'm completely baffled by this weird behavior. Any insights? Thanks.


texts: What are the most popular software development methodologies used by game studios?

texts:
What is the best (as in most used by professional game developers and/or companies) software development methodology used in game development?

I've heard that SCRUM is popular, but i'm not sure.


texts: Rotation on one object affects all others

texts:
I am making a game using LWJGL. I have encountered a problem with rotation, looked it up, found a solution, and added it, but it doesn't entirely work.
In the code below, the bottom section is rotating well, but when the top one is rotating the other direction, the same direction, or anything else relating to rotation, the bottom sprite seems to move with it, or cancel out the rotation altogether.
            GL11.glPushMatrix();
            GL11.glTranslatef(0.0f, 0.0f, -300f);
            GL11.glRotatef(i+=0.5f, 0.0f, 0.0f, 1.0f );
            drawStar2(0, 0, 0);
            GL11.glLoadIdentity();
            GL11.glPopMatrix();

            GL11.glLoadIdentity();

            GL11.glPushMatrix();
            GL11.glTranslatef(0.0f, 50.0f, -300f);
            GL11.glRotatef(i-=0.5f, 0.0f, 0.0f, 1.0f);
            drawStar0(0, 0, 0);
            GL11.glLoadIdentity();
            GL11.glPopMatrix();

How can I make the rotation of the object in the code on the bottom insensitive to the rotation of the object in the code at the top?
I am also using Slick-Utils, if this is also causing a problem I haven't heard of.


texts: Unity blocked after changing Time region

texts:
I reinstalled Windows then Installed Unity. Then I changed my timezone from US Pacific to Europe where I actually live. Unity got blocked: "Expired licence" even though I use the free version. https://forum.unity.com/threads/expired-license-on-free-version.90072/

If I change my timezone back to US Pacific Unity works (Took me 2 hours to figure out it was the timezone btw). I tried reinstalling Unity from scratch, didn't work. How can I change timezone back to Europe without locking up my Unity licence?


texts: I am making a game that has objects that shoot other objects. I need the enemies to follow a path. The easiest way I can think of doing this is by having an array of coordinates and they move between them. But when I make a curve in the path, I don't want to have to put in 100 coordinates. There must be a better way.


texts: Issue with script recognizing particular z-axis rotation angles in Unity

texts:
I'm trying to make a simple flowing pipe-style rotation puzzle, but having issues getting Unity to properly recognize certain angles of rotation. My rotation script for the pieces:

private void OnMouseDown()
    {
        if (!GameControl.winState)
            transform.Rotate(0f, 0f, 90f);
    }

If the value of the z rotation is set to 90 or -90, the game works fine. However, if I try a different value such as 60 or 30 (and have corresponding 60 or 30 shifts to the puzzle hexes' z rotations to scramble the puzzle), the game fails to note a win state. Here is the game control script:

public Transform[] hex;
public GameObject successLight;

public static bool winState;

void Start () {
    successLight.SetActive(false);
    winState = false;
}

void Update ()
{
    if (hex[0].rotation.z == 0
        && hex[1].rotation.z == 0
        && hex[2].rotation.z == 0
        && hex[3].rotation.z == 0
        && hex[4].rotation.z == 0)
    {
        Debug.Log("PuzzleSolved!");
        winState = true;
        successLight.SetActive(true);
    }
}

I've also tried making the rotation using Euler angles, but still experienced the same problem. Is this an issue with the rotation not being exact and therefore unable to meet the conditions? Checking the inspector as the game runs, it looks as if even when the hexes all get to the proper z rotation of 0, the win state still isn't triggering when the rotation moves at a degree other than 90. Any help would be appreciated, feeling very confused at the moment.