texts: How do I stop my gun from pointing at the player?

texts:
I'm making a game where you shoot enemies in Unity, but I can't figure out how to stop the player from pointing the gun at himself.
I've tried detecting if the gun is on the left side of the player and if it's rotation on the z-axis is less than 0, but no luck

Here's the code for the gun:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GunController : MonoBehaviour
{
    public bool testbool;

    public Transform player;
    public CharacterController2D playercontroller;
    public float smoothness = 0.125f;
    public float winglength = 2;
    private Vector2 difference;
    bool facingright = false;

    public GameObject bullet;
    public int maxammo;
    private int ammo;
    private bool firing;
    public Vector3 bulletspawnpos;

    private SpriteRenderer sprite;
    public Texture2D normalGun;
    public Texture2D emptyGun;
    public GameObject emptyBottle;
    // Start is called before the first frame update
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        player = transform.parent.transform;
        ammo = maxammo;
    }

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

    }
    private void FixedUpdate()
    {
        firing = false;
        bool wasfacingright = facingright;
        if (Input.GetMouseButton(0) & ammo !>= 0 & !firing )
        {
            firing = true;
            Instantiate(bullet, transform.position+bulletspawnpos, transform.rotation);
        }
        if (player.transform.position.x - transform.position.x < 0)
        {
            facingright = false;
            sprite.flipY = false;
        }
        if (player.transform.position.x - transform.position.x > 0)
        {
            facingright = true;
            sprite.flipY = true;
        }
        if (wasfacingright != facingright) { playercontroller.Flip(); }

        difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float rot = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;

        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition) - player.position;
        pos.z = 0;
        Vector3 desiredpos = player.position + (winglength * pos.normalized);
        Vector3 smoothpos = Vector3.Lerp(transform.position, desiredpos, smoothness);
        transform.position = smoothpos;
        transform.rotation = Quaternion.Euler(0, 0, rot);

    }
}

Before you point out that the ammo doesn't go down, just know I didn't add that for testing purposes.


texts:
I have a virtual joystick to rotate the player and this piece of code works nice and smooth for the rotation of the players view.

public void rotatePlayer(Vector3 newPosition){
  transform.Rotate(new Vector3(-newPosition.y,newPosition.x,0)*Time.deltaTime);
}

I pass a Vector3 with the position of the joystick in relation of his parrent's(the joystick border) anchor.That gives me the rotation direction.Which means that if I set the rotation of the camera direclty it will just flip to that point and not move progresively to that point.

Even though z is set to 0 in the vector3, it changes the z axis angle of the camera. How can I clamp it to 0 without using many resources?

I tried other methods but they just switch the camera's rotation directly when the joystick is touched like I already said.Flip and stop.

I guess I could just set the z axis rotation to 0 every time but that just seems like double work.


texts: OpenWorld SceneGraph management and optimization

texts:
I have a SceneGraph class which for now is just a simple list implementation, and the only optimization I've planned so far is a check is something like this:

//GetDistance returns the distance between 2 objects
float maxViewDistance = 10.0f;

for(int i = 0; i < sceneList.count; i++)
{
    if(GetDistance(sceneList[i], playerObject) < maxViewDistance)
    {
        Renderer.Draw(sceneList[i]);
    }
}

I plan on filling the SceneList when loading the game from a file which has a bunch of objectIDs and their positions, and then loading each object data (like .FBX, .BMP) somewhere (in another file).
But since I don't intend on having loading screens (except when the game starts), wouldn't it become too much to iterate when drawing? For example if I have a sceneList with a million objects for the entire game, even if it's just checking an if for each objects, wouldn't that hurt performance?

I was thinking in making a sublist that will get populated only for the objects I'm currently drawing (that are less than the maxDistance I set), but then I'd need to update this subList everytime the player takes a step, and I'd need to check for all objects in my entire objectList to see which are going to be draw next, so I don't think it'll help anyhow.

Also, for physics, I was also iterating through my sceneList and forcing every object to my physics rules (only gravity for now), but if I add for collision checks, what's the best way to do it?

//Inside my game update function
for(int i = 0; i < sceneList.count; i++)
{
    UpdatePhysics(sceneList[i]);
}

[...]

void UpdatePhysics(Object* object)
{
    //I'd need to check for collisions against **all** objects inside my sceneList again? Isn't there a better way to do this?
}

How games such as WoW (open world with no loading screens between large amounts of zones) do?
And for Physics, such as Deus Ex, where any object you throw in the air will be affected by gravity and will have collision against wherever is in it's path?


texts:
I'm making a game for an assignment at university.
The game I am making requires random household appliances around a house to "turn on" at random times.
The player must run around the house turning this off.

I am confident with the rest of the code for the game, but the random turning on is what I'm not sure on.

I am thinking the solution would be to use an array with all my appliances pushed into into, then create a timer event.
From this a random time would be picked from the timer, and then a random appliance would be picked from the array. The appliance on animation would then be displayed until the player clicked on it to turn it off.

Only problem is i'm not sure how to start this.

Also worth mentioning, I am only able to use flashdevelop and AS3 for this project, so no Adobe Flash.

Thanks in advance,

Job4aCowboy


texts: How do I make three attack systems so that there is a rock-paper-scissors distribution, but equal average?

texts:
In the game, there are three attack systems: Strength-based, Magic-based, and Psionic-based.

The damage each type deals will be multiplied by their own modifier. The one for strength I have come up with is ((3 d6 rolls)*10+Luck)/100.

How can I make similar calculations (willing to not use the one I came up with, but would like to do something similar) so that the Strength one beats the Magic one more often than not, the Magic one beats the Psionic one more often than not, and the Psionic one beats the strength one more often than not, by roughly the same amount on average.

I know that this sort of thing is possible.

If you take four spinners with six numbers, (5,4,3,5,4,3) loses 2 out of 3 to (6,6,0,0,6,6), which loses two out of three to (7,1,7,1,7,1), which loses 2 out of 3 to (2,2,8,8,2,2), which loses 2 out of 3 to (5,4,3,5,4,3).


texts: Perlin noise terrain generation with integer (discrete) elevation levels results in artifacts at rounding boundaries

texts:
I am trying to generate terrain with discrete height levels using Unity's built in 2D Perlin noise function. The output is a float in [0,1]. I then scale the float linearly to a range [minimum Height, Maximum Height], and round it to the nearest integer.

The problem is that this results in artifacts at rounding boundaries, as can be seen in the following image:

As you can see, the ridge line partially marked in red should not be there. It is created because that's the rounding boundary, meaning that this is the line between x.49 and x.50 (x is integer), so the x.49 is rounded to x, while the x.50 is rounded to x+1.

I'll demonstrate that by zooming to a part of the image and showing the height value of different blocks:

The height of Block 1 is 14.48

The height of Block 2 is 14.52

The height of Block 3 is 15.6

The height of Block 4 is 14.6

As you can see, the only reason there is a ridge between Block 1 and Block 2, is because 1's height is rounded to 14, while 2's height is rounded to 15. This is unlike Blocks 3 and 4, which should have an elevation difference between them as per the Perlin noise function.

I can of course use Floor or Ceil or other methods to turn the float result from the Perlin Noise function into an integer, but that simply results in artifact lines appearing at other places.

Any help in solving this issue would be greatly appreciated.

Thank you.

Edit:

Here is how I get the height of each column:

float grassHeightFloat = WorldGenMath.getNoise(x + grassHeightRandOffSet, z + grassHeightRandOffSet,
            grassSmoothness, grassMinHeight, grassMaxHeight)

uint grassHeight = Convert.ToUInt32(grassHeightFloat);

WorldGenMath is:

private static float scaleNoise(float value, float minScale, float maxScale)
    {
        return scale(value, 0, 1, minScale, maxScale);
    }
private static float scale(float value, float min, float max, float minScale, float maxScale)
    {
        float scaled = minScale + (float)(value - min) / (max - min) * (maxScale - minScale);
        return scaled;
    }
public static float getNoise(uint x, uint z, float smoothFactor, int minScale, int maxScale)
    {
        float noise = Mathf.PerlinNoise(x * smoothFactor, z * smoothFactor);
        return scaleNoise(noise, minScale, maxScale);
    }
public static float getNoise(long x, long z, float smoothFactor, int minScale, int maxScale) {
        return getNoise(Convert.ToUInt32(x), Convert.ToUInt32(z), smoothFactor, minScale, maxScale);
    }


texts: Algorithm to simplify building/structural meshes

texts:
I am looking for an algorithm to simplify the meshes of buildings or similar structures.

EDIT: I had made a comment that Hoppe's algorithm tends to make meshes more and more spherical with simplification. But, I am not sure about it, so am deleting the comment. Buildings in contrast should tend to become more and more rectangular with increasing simplification. The D3DX extensions for D3D in version 9.0 (d3dx9.lib) used to have classes to do progressive mesh simplification. See:
http://doc.51windows.net/Directx9_SDK/?url=/directx9_sdk/graphics/reference/d3dx/functions/mesh/d3dxgeneratepmesh.htm
http://msdn.microsoft.com/en-us/library/windows/desktop/bb281243(v=vs.85).aspx


texts: Is it possible to use the Unreal Engine as a big C++ library, without using the editor?

texts:
I want to write a game entirely in C++, but I would like to profit from the possibilities offered by the Unreal Engine, especially in terms of graphics and physics. Nevertheless, I strongly dislike its visual editor: I find it heavy, slow and unintuitive. Finally, it forces me to use Visual Studio instead of my favourite C++ IDE.

Is there a way to use the Unreal Engine as a big library that I could simply include in my C++ project, or am I forced to used the Unreal Editor?

Related question for Unity: How can I build a game in Unity with minimum/no use of the visual editor?


texts:
I am writing a really simple game with a scene (horizontal plane) and a human moving to the right of the plane (watching the simulation from the +z axis).

The scene contains some trees, which I am moving towards -x axis in order to create the animation effect (by adding a float to their current position).

The human just walks or runs with increasing/ decreasing the angular velocity of one of his legs.

The question comes down to, how can I combine this two entities in order to correlate the change of the speed of the human with the change of the variable that is responsible for making the animation of the scene?

Should I convert the angular velocity to velocity?


texts:
So I am implementing a deferred rending model for my engine, and I want to be able to send all scene geometry into a single shader to calculate ambient, diffuse, normal, ect thats not the question.
Once I have all of this data buffered into the GPU I can render all of that geometry from a camera perspective defined by a uniform for the cameras position in the scene. I am wondering if I can reuse this model data already in VRam in another shader translated by a light sources projection matrix to calculate the shadows on this scene geometry without needing to send the same data to the GPU again.
Is there a way to tell my light shader, hey all that juicy geometry/scene data you want is already in V-Ram, just use this matrix transformation instead.
Alternatively when I am sending the VAO to the GPU is there a way to send it to two shades in parallel, one for the deferred rending model, one for shadow casing light sources?
Thanks so much!


texts: How to manipulate PostProcessing effects settings during execution with c#?

texts:
I need to change the intensity value of my current Vignette effect depending in specific conditions.
So far I haven't been able to achieve this. Please help!

Image of what I want to achieve:

My setup:

Unity 2019.3.5f1 with URP implemented
Post Processing Package (v2) installed
Scene with a GameObject + Volume component with Vignette and Bloom effect overrides added
A monobehaviour component script in the very same GameObject from above

My monobehaviour script:

using UnityEngine;
 using UnityEngine.Rendering.PostProcessing;

 public class PostProcessingHandler : MonoBehaviour
 {
   private PostProcessVolume _ppv;
   private Vignette _vignette;

   // Vignette intensity values
   [SerializeField, Range(0f, 1f)]
   private float _lowIntensity = 0.25f;
   [SerializeField, Range(0f, 1f)]
   private float _highIntensity = 0.5f;

   private void Start()
   {
     _ppv = GetComponent<PostProcessVolume>();
     Debug.Log(_ppv);
   }
 }

When I try to retrieve PostProcessingVolume component to get it's profile (and further layer manipulation) I always get "null".

Image of my setup:

I've seen several guides/posts and even Unity documentation but I cannot get past that starting point of getting the PostProcessingVolume component, what am i missing?


texts: fbx material show correctly in unity but import to maya show wrong material

texts:
see my gif, fbx material work well in unity preview, but when import it in maya, face material show wrong

here is my fbx

I use unitychan material in this unity asset

in unity

in maya

the strange thing is in maya I use eye image material but show pure color material


texts:
Learning Unity for 2D development, I want to create a text label.

So far, I have been using GUI.Label to write the text. It is above my sprite:

I would like to rotate the label relatively to the monster. In other words:

How can I achieve this? I have a feeling that OnGUI() is probably the wrong solution.


texts: How to remove floating terrain when generated with 3D Perlin Noise?

texts:
I'm currently using 3D Perlin Noise to generate random terrain in combination with Marching Cubes.

My issue seems to lie in scaling the noise function to get reasonable heights in my terrain. If only one octave is used, all points in relation to the noise are obviously interpolated which results in fairly smooth data. However, to get overhangs/caves/jagged terrain, I have to use multiple octaves with varying amplitudes and/or scale the resulting values to my 'max' height I want of the map.

I might be missing something, but by using marching cubes with 3D perlin noise, I regularly get floating bits of terrain.

Any ideas on how I could correct this or if there's other noise functions I might use to get results like I'm describing? I'm wanting hills/valleys/mountains/lakes/etc. No need for floating bits segregated from the rest of the map. I believe this is a similar issue to what Minecraft has when it has terrain that just floats around in the sky occasionally upon generation.

Thanks for any assistance,
Mythics


texts:
I'm developing an multiplayer game "from scratch" (not using a big Engine-Suite like Unity but the lower-level libgdx).

Currently I've got a NetworkManager which handles the sending of messages on server side and
receiving those with subsequently calling methods on client site.

At the moment the sync between figures works already once they are correct configured and spawned on both ends.
Now I'm currently think about the spawning of those objects.

Approach No.1:
My first approach was that every time the Server spawned a new (e.g.) player, it will subsequently send a
"SpawnObjectMessage"-Object (holding all necessary type and configuration values) to all clients.
Clients will than spawn a new player-figure. Now the synchronization works.

Concerns:

I have concerns with this solution that individual messages could be lost (due to network problems, for example),
or what happens if a client closes the program in the middle of the game and then starts again and all figures have
to be reloaded (as already said : The server only sends the message once as soon as it spawns a player itself).

Approach No.2:
The server hold a "model" of all figures (he does this anyway due to some other functionality) and sync this with all clients.
The "model" here is a list of objects each one describing values of a figure:
The

prefab/class/type the object is
if it is spawned of or just created on server side
is it controlled by a player and possibly the PlayerID
...
The server will send the complete List (or only the changed entries) to all clients every time some changes occur.
The clients will override their local list and subsequently iterate over it and spawn objects if they could not find
a corresponding counterpart. If a new Player enters the game or a client restarts the game, the server will resend
the complete list to the new client.

Concerns:

This solution seems a little bit "reactive"
It maybe not very intuitive
Maybe I'm overseeing something what will bring problems

Which approach is more common or what concerns are you aware of in such projects?

edit/additional informations:

Since @milk asked how Updates works here is an additional explanation how this will work:
The server will send continously update messages (e.g. "UpdatePositionMessage") for every Player-Objects exiting/spawned on server side.
Server will keep doing so no matter if clients has successfully spawnend the corresponding counterpart object or not. Clients will simply
ignore updating objects which can't be found. This update-mechanism is used in both approaches described above.


texts:
I'm making a rolling-ball type game, and I can't seem to get my sphere-mesh collision code working properly.

Currently what I have for the main loop (in regards to collision) is the following:

Calculate player acceleration based on input
Clamp velocity to avoid clipping
Add velocity to position
Add acceleration to velocity
For each solid object:
    Check for collision for this object and resolve (how I do this is below)

If there were any collisions:
    Normalize accumulated normal vector (explained below)
    Slow down ball to account for friction

I tried two main methods for resolving collisions, each with their own problems.

The first method:

For each triangle:
    If there is a collision:
    Correct player velocity along normal based on distance
    Accumulate normal for friction calculations later
    If velocity perpendicular to surface is above threshold:
        Rebound ball off surface with damping factor
    Otherwise, if moving toward surface instead of away:
        Clear perpendicular velocity

The problem with this method is, when I hit a wall, the player will begin to bounce erratically. The collision I'm using to test this looks like this (player to scale):

The second method is similar to the first:

Set collision distance accumulator to arbitrarily high value
Set triangle index to -1 (to denote that there's no collisions)

For each triangle:
    If there is a collision:
        Calculate collision distance
        If this distance is smaller than the accumulator value:
            Set triangle index to current triangle
            Set collision distance accumulator to current distance value

If the index is not -1 (there was a collision):
    Correct player velocity along normal based on distance in accumulator
    Accumulate normal for friction calculations later
    If velocity perpendicular to surface is above threshold:
        Rebound ball off surface with damping factor
    Otherwise, if moving toward surface instead of away:
        Clear perpendicular velocity

This fixes the bounciness issue, but now I can go partially through surfaces which are supposed to be solid.

I have no idea where to turn at this point. Hopefully someone here can provide some insight as to what's going on.

[EDIT] I can add some video if that'd help anyone.

[EDIT 2] Here's a link of a video using the first method:
https://drive.google.com/open?id=1n1MxTYQkzKA2eixTkEOD3E7eOd0Ryl4f

[EDIT 3] I redid the code somewhat, here's some related code snippets:
https://pastebin.com/GQd9bwgB

It still bounces, like so:
https://drive.google.com/open?id=1JPJ4lkIB0wBhjnlT5mawxKwq0dC6DlNr

I think I know the cause, but I don't know how to best fix the issue.


texts: Is there an alternative to VBOs or deprecated functions to draw many small quads?

texts:
I was thinking about how to program a user interface in a 3D game. The problem is, immediate mode (glBegin and glEnd) is deprecated for a long time but I don't think vertex buffer objects (or arrays) are needed just for the (2D) quads I want to draw (and I don't think they are even efficient for plenty of small quads).

Are there any approaches on how to avoid vertex-buffer-objects/arrays and the deprecated functions?


texts: Gameobject with Canvas child (Unwanted inspector behavior)

texts: When I try to focus (by double clicking or pressing f) on gameobjects in my scene which have a Canvas as a child, the scene view zooms out to show the Canvas. I would like to be able to see the gameobjects themselves when focusing on them. Is there a way to do this?


texts:
I'm working on simple platformer game. I've got already finished programming the main part of game, which is moving and collecting items.

I want a unique game puzzle in every level, but I can't think up enough. I've been thinking for hours but I've got only few puzzles which are not very good. I would be grateful for any ideas or help you can provide.


texts: Rigidbody player controller on moving platforms

texts:
So basically, I was trying to make moving platforms. When I finished my prototype, I noticed that the movement on the platform is very wobbly:
https://www.youtube.com/watch?v=hmBumsrlHGA&feature=emb_logo
To snap the player onto the platform, I am just making it a child of the platform. Anyway, I don't know what is causing this issue and was wondering if I can get any help. Thank you in advance
Here, the controller code:
private void Movement()
    {
        //Extra gravity
        rb.AddForce(Vector3.down * Time.deltaTime * 10);

        //Find actual velocity relative to where player is looking
        Vector2 mag = FindVelRelativeToLook();
        float xMag = mag.x, yMag = mag.y;

        //Counteract sliding and sloppy movement
        CounterMovement(x, y, mag);

        //If holding jump && ready to jump, then jump
        if (readyToJump && jumping) Jump();

        //Set max speed
        float maxSpeed = this.maxSpeed;
        if (sprinting)
        {
            this.maxSpeed = 25;
        }
        else
        {
            this.maxSpeed = 15;
        }

        if(sprinting && y < 0)
        {
            this.maxSpeed = 15;
        }

        //If sliding down a ramp, add force down so player stays grounded and also builds speed
        if (crouching && grounded && readyToJump)
        {
            rb.AddForce(Vector3.down * Time.deltaTime * 3000);
            return;
        }

        //If speed is larger than maxspeed, cancel out the input so you don't go over max speed
        if (x > 0 && xMag > maxSpeed) x = 0;
        if (x < 0 && xMag < -maxSpeed) x = 0;
        if (y > 0 && yMag > maxSpeed) y = 0;
        if (y < 0 && yMag < -maxSpeed) y = 0;

        //Some multipliers
        float multiplier = 1f, multiplierV = 1f;

        // Movement in air
        if (!grounded)
        {
            multiplier = 0.5f;
            multiplierV = 0.5f;
        }

        // Movement while sliding
        //if (grounded && crouching) { multiplierV = 0.5f; multiplier = 0.5f; }

        //Apply forces to move player
        rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
        rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
    }


texts: Picking problem with rotated view matrix

texts:
I have picking code that works, if my view matrix has no rotation (only translation). Now If I rotate my camera, picking goes to hell.

I cant find whats wrong

My code:

/*-----------------------------------------------------------
Function:   GetViewportSystem
Returns:
    viewportCoordSystem

Get viewport coordinate system (only for reading)
Forward ray goes through origin
d = distance |camera, projection plane|
cameraPos = position of camera in World Space
lookAt = camera target in World Space
-------------------------------------------------------------*/
ViewportCoordSystem Camera::GetViewportSystem() const
{
    ViewportCoordSystem viewportCoord;
    viewportCoord.w = this->cameraPos;
    viewportCoord.w = this->cameraPos - this->lookAt;
    viewportCoord.w.Normalize();

    viewportCoord.u = MyMath::Vector3::Cross(viewportCoord.w, MyMath::Vector3::UnitY());

    viewportCoord.v = MyMath::Vector3::Cross(viewportCoord.u, viewportCoord.w);

    float d = (this->viewport.Height * 0.5f) * (1.0f / tanf(this->viewport.fov * 0.5f));

    viewportCoord.origin = this->cameraPos;
    viewportCoord.origin -= d * viewportCoord.w;

    return viewportCoord;
}

/*-----------------------------------------------------------
Function:   MapViewport2Dto3D
Parametrs:
    [in] viewportSystem - cameras viewport coordinate system
    [in] point - 2D point on image
Returns:
    3D mapped point in space

Map 2D image point to 3D space
Info about mappind 2D to 3D: http://meatfighter.com/juggler/
-------------------------------------------------------------*/
MyMath::Vector3 Camera::MapViewport2Dto3D(const ViewportCoordSystem & viewportSystem, const MyMath::Vector2 & point) const
{
    MyMath::Vector3 res = viewportSystem.origin;
    res += (point.X - this->viewport.Width * 0.5f) * viewportSystem.u;
    res += (this->viewport.Height * 0.5f - point.Y) * viewportSystem.v;

    return res;
}

And calculating ray (x, y are mouse coordinates within screen, my world is scaled, so I amd trasnforming ray and origin to transformed world)

    ViewportCoordSystem vpSystem = this->camera->GetViewportSystem();
    MyMath::Vector3 pos = this->camera->MapViewport2Dto3D(vpSystem, MyMath::Vector2(x, y));

    float inverseScale = 1.0f / scale;
    MyMath::Matrix4x4 worldInv = MyMath::Matrix4x4::Scaling(inverseScale, inverseScale, inverseScale);

    this->ray.dir = pos - this->camera->GetPosition();
    this->ray.dir = MyMath::Vector3::TransformCoordinate(this->ray.dir, worldInv); //transform ray to object space
    this->ray.dir.Normalize();

    this->ray.origin = this->camera->GetPosition();
    this->ray.origin = MyMath::Vector3::TransformCoordinate(this->ray.origin, worldInv); //transform ray to object space


texts: Unity - How to add bones to procedural mesh

texts:
Basically this is the set up: An N amount of prefabs are bundled together into a new GameObject. This is then merged into a single main mesh composited of M amount of material submeshes.
The shape is standing upwards on the Y axis and is a bunch of arms.
The goal is to move these by adding bones.

I wasn't able to find many examples on how to properly assign bones to a procedural mesh which isn't a simple cube.

The problem is assignment of vertices to the boneweights. I'd like for the transform Y=0 vertices to have no weight and the Y=furthest vertices have full weight. I am not sure how the assignment should be done.. Any pointers? :)

So far the Lower and Upper bone transforms are in the right place, but when moving them the mesh isn't bending as I hoped it would in a nice curve, half of the vertices are simply moved uniformly with a thin mesh line connecting the two halves.

private void _AddBones()
{
    if(m_SkinnedRenderer != null)
    {
        // Make bone weight for vertices
        BoneWeight[] weights = new BoneWeight[m_MainMesh.vertexCount];
        int halfway = (weights.Length / 2);
        for (int i = 0; i < weights.Length; i++)
        {
            if(i < halfway)
            {
                weights[i].boneIndex0 = 0;
                weights[i].weight0 = 1;
            }
            else
            {
                weights[i].boneIndex0 = 1;
                weights[i].weight0 = 1;
            }
        }

        m_MainMesh.boneWeights = weights;

        // Make bones and bind poses
        Transform[] bones = new Transform[2];
        Matrix4x4[] bindPoses = new Matrix4x4[2];
        bones[0] = new GameObject("Lower Bone").transform;
        bones[0].parent = m_MergedRoot.transform;
        bones[0].localRotation = Quaternion.identity;
        bones[0].localPosition = Vector3.zero;
        bindPoses[0] = bones[0].worldToLocalMatrix * m_MergedRoot.transform.localToWorldMatrix;

        bones[1] = new GameObject("Upper Bone").transform;
        bones[1].parent = m_MergedRoot.transform;
        bones[1].localRotation = Quaternion.identity;
        bones[1].localPosition = new Vector3(0, 1.5f, 0);
        bindPoses[1] = bones[1].worldToLocalMatrix * m_MergedRoot.transform.localToWorldMatrix;

        m_MainMesh.bindposes = bindPoses;
        m_SkinnedRenderer.bones = bones;
        m_SkinnedRenderer.sharedMesh = m_MainMesh;
        m_SkinnedRenderer.rootBone = bones[0];
    }
}


texts: How to break the feeling of busywork in a game

texts:
I don't know if this topic has been explored before but in a handful of games I've played there comes a point where trying to explore everything, doing sidequests, or even trying to get gear starts feeling like busywork. That sort of feeling makes me less interested in the game, and I usually wind up either just stopping playing altogether or just breezing through the rest of the game just to get it finished and out of the way. This feeling seems to happen mostly with RPGs from my own personal experiences.

How do you prevent activities the player can do (sidequests, exploration, item crafting, etc.) from feeling like artificial time padding or busywork?


texts: How can I debug live multiplayer servers effectively?

texts:
I have a multiplayer server made by a small team of developers and we have bugs that crop up on our live server occasionally that we simply can't reproduce while playing with our small team on a live server.

It clearly isn't feasible to attach a debugger and halt the world on a live shard... so what are some effective strategies in debugging multiplayer games while they are still running?

Attaching a debugger is fine on a developer server, but perhaps not always feasible to reproduce the bug or always effective.


texts: Why set the position of both b2Body and Box2DSprite?

texts:
In a game, we add a body for each sprite, the method is:

createBodyAtLocation:(CGPoint) forSprite:(Box2DSprite*)sprite

In which we create the body and we attach it to the sprite in parameter: sprite.body = body;

Then we set the position of the body, but later on in the code, in the update method, we also set the position of the sprite to the same position as the body. I was wondering: Why are we doing it twice? As we already set the position of the body in the world, and we made a link between the two with sprite.body?


texts:
I hear pros playing Fortnite that have 20-50 ping complain that they cannot perform as well as pros with 0 ping due to wall taking, etc. It's easy to think that a 20ms ping difference is negligible but it is not in competitive situations.

It seems to me that it should be possible to standardize a lobby's ping to the current maximum player's ping at any given moment. Obviously in a competitive game like Fortnite, the worst ping a pro player can have is generally 50-60 ping.

This solution would involve psuedo latency. For example, in competitive Fortnite, if the worst ping among the players is 50, then all players will be forced to also have 50 ping by inducing an artificial server response delay. This would allow no single player to have an advantage based on internet connection.

How could I implement a feature like this, to provide a level playing field?


texts: Fundamental Questions: Building vs Compiling vs Rendering vs Coding vs Running?

texts:
I'm using Urho3D on Raspberry Pi, but the following questions apply to all platforms.

What should I do in order to reduce the load of online real-time rendering of the game? Does building/compiling/rendering the game (before running it) makes it easier and lighter to be run afterwards?

When making animations with 3dsmax, we use high-end computers to design the animation and render it. After that, any low-end and simple computer can play the animation. Now can we use a similar approach? Can I build/compile/render the game in a high-end machine and run the game in a low-end machine?

What is exactly the difference between building/compiling/rendering when designing a game, and running/real-time-rendering when playing the game?

Does a game needs rendering when after designing? Or all the renderings all left to the playing time!?


texts: Are abilities in online games better crafted in the main game backend language or a scripting language?

texts:
Scourge Healing: Hex Spell. (30 seconds.) Whenever target foe is healed, the healer takes 15...67...80 holy damage.

The above is one of Guild Wars 1's monk class skills.

My question is about what would be a good way of implementing abilities like this. In a realtime game, should I be implementing them in my game's backend language(golang) directly, interpreting them from a scripting language at runtime, or something else? How do most RPGs(online or otherwise) do this?


texts: Why do I get this error when setting up Android support for Game Maker?

texts:
Game Maker asks me to install the Android SDK API 13 for it to work. I opened the SDK Manager and clicked at API 13 but I wasn't able to click the "install packages" button.

I clicked at the obsolete and then I was able to install. But when I pressed "Accept Licence" I wasn't able to click install as an error came out:

Package Google Tv Addon, Android API 13, revision 1 (Obsolete) depends on Missing SDK Platform Android, API 13".

Any help would be much appreciated.


texts:
I encountered a strange RenderTarget issue, in XNA/Monogame.

I am currently updating my render target at every frame, just to test to see what is happening.  When I move the camera around, the positioning of the drawing inside of my rendertarget moves as well.

Notice in the example, how the image moves inside of my render target:

Here is the code for the Render Target draw:

GraphicsDevice.SetRenderTarget(Render);
RoundLineManager.Draw(Branches.GetAllObjects(), new Color(102, 50, 18), Matrix.Identity * Camera.View * Camera.Projection, RoundLineManager.TechniqueNames[0]);
SpriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, Camera.View);

foreach (Pool<Leaf>.Node l in Leaves.ActiveNodes)
    if (l.Item.Visible)
        l.Item.Draw();

SpriteBatch.End();
GraphicsDevice.SetRenderTarget(null);

Here is the related Camera properties:

public Matrix View
{
    get
    {
        return Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f + shakeOffset.X, ViewportHeight * 0.5f + shakeOffset.Y, 0));
    }
}

public Matrix Projection
{
    get
    {
        return Matrix.CreateOrthographicOffCenter(0, Infinidrill.GraphicsDevice.Viewport.Width, Infinidrill.GraphicsDevice.Viewport.Height, 0, 0, 1);
    }
}


texts: Why can´t this boolean stop the sound from playing 60 times a second?

texts:
The code:
local dontPlayMoreThanOnceDammit = false

function Behavior:Awake()
    local sound = CraftStudio.FindAsset( "motorbuson1" )
    self.mySoundInstance = sound:CreateInstance()
    self.mySoundVolume = 1.0
    self.mySoundInstance:SetLoop( true )
    self.mySoundInstance:SetVolume( 1.0 )
 end

function Behavior:Update()
    if dontPlayMoreThanOnceDammit == false and CraftStudio.Input.WasButtonJustPressed( "on" ) then
        self.mySoundVolume = 1.0
        self.mySoundInstance:Play()
        dontPlayMoreThanOnceDammit = true
    end
    if CraftStudio.Input.IsButtonDown( "off" ) then
        self.mySoundInstance:Stop()
        dontPlayMoreThanOnceDammit = false
    end
end

Error it gives:


texts: Writing C# for iPhone 2D Game Dev - Not Unity

texts:
What are my options for writing C# code to produce a 2D iPhone game?

I specifically mention 2D -- Unity will not suffice for me (even though it can "fake" it with a 2.5D game).

I like C# because of language features (LINQ, garbage collection, generic collections, etc.) although I would be open to considering Java as well if nothing exists. Objective C is not my cup of tea.

And I don't own a Mac. Eek.


texts: How do I convert a cube map to an equirectangular projection?

texts:
I have a cube map texture showing a surrounding area, which I want to pass to a program that only works with latitude/longitude maps.

How can I do this?

In other words, I need to turn this:

…into this (I think it's additionally rotated -90° over the x axis):


texts:
I was just trying and make a simple 2D game. I have a simple circle sprite (red, green and blue). These circles fly upwards with my scripting as shown below:-

public class Direction : MonoBehaviour {
    public GameObject[] ballons;
    public float increase;
    public float timeInterval;
    public float timeForGetGo;
    public float increaseInterval;

    public float startTime;
    public float timeForNextSpawn;
    public Transform instantiatePos;
    void Start () {;
        StartCoroutine (direction ());

    }

    void Update () {
        increase += increaseInterval;
        direction ();
        Instantiater ();
    }

    IEnumerator direction (){
        while (true){
            foreach (GameObject gameObjects in ballons) {
                gameObjects.transform.position = new Vector3 (gameObjects.transform.position.x, gameObjects.transform.position.y + increase, 0f);
                yield return new WaitForSeconds (timeInterval);

                }
                }

So, instead of making them fly with one script by one script, which I normally do, I tried to make array of these gameObjects and make them go upwards. **It worked great!** But, I have a problem. I want these upward going circle to instantiate but when I instantiate them, they won't go upwards as they aren't in the list of arrays I put earlier as in:-

public GameObject[] ballons;

in first line in that script.

So, as in conclusion, my problem is the instantiated objects won't have same property coz the script is attached to another gameobject and not in the original gamobject itself. Any ideas?


texts: Why does my value increase a ton when the tab switches from inactive to active?

texts:
I basically have a lerp function similar to this one: Client interpolation for 100% serverside game when a new server update is received, the update frequency is added to a variable (msAhead) and the delta is subtracted from it every client frame. But when I do it the variable msAhead increases a lot when the tab is switches from inactive to active. Here is my code:

msAhead += updateFrequency; //when new update is received.

(function loop(now) {

var now = Date.now();
delta = now - Time;

Time = now;

msAhead -= delta;

console.log(msAhead);

requestAnimationFrame(loop)

    })(0);

How can I fix my issue?


texts:
I remember someone saying "24 fragment pipes on nVidia 7800" in a presentation.

Am I correct in saying that a fragment is the data that can generate a pixel in the frame buffer? Or are fragments the same thing as pixels? I'm getting confused here.

What is a fragment pipe?


texts: How can I draw lines in editor between waypoints when creating the waypoints?

texts:
public List<Vector3> destinations = new List<Vector3>();
    public int numberOfDestionations;
    public float moveSpeed = 5f;
    public bool loop = false;
    public bool moveBack = false;
    public Text textCounter;

    private Coroutine movementCoroutine;
    private bool pause = false;
    private bool coroutineRunning = false;
    private Vector3 startPosition;
    private int countDestionations;

    private void Start()
    {
        for (int i = 0; i < numberOfDestionations; i++)
        {
            destinations.Add(new Vector3(UnityEngine.Random.Range(-300, 25), -1f, 0));//25, -1f, 0);
            if(i > 0)
            {
                Gizmos.DrawLine(destinations[i], destinations[i + 1]);
            }
        }

I'm trying to use gizmos but getting exception :
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

On line 33 :
Gizmos.DrawLine(destinations[i], destinations[i + 1]);

I want that while it's creating the vectors draw lines from the current created vector destination and the next one. A line from index 0 to index 1 to index 2 and so on. So when running the game I will see a net of all the lines connected between the vectors destinations.


texts: MonoGame - Ordering Movement Key Presses

texts:
I'm looking for a way to retrieve the last key pressed even when other keys might be pressed for a top-down four-directional game. For example:

W is pressed → Move up
D is pressed → Move right
S is pressed → Move down

The above I can get to work fine using a stack. When S is released, then we start moving right again, and when D is released, we go back to moving up. The issue arises when trying to release (say W) and then pressing W again to move up before S and D are released.

I've tried using arrays and lists to solve this problem (to use flags or remove a key from any point in the collection), but it results in whatever key is last in the if statements to check for the movement keys being given the priority.

Any help is greatly appreciated. If there's anything else I could provide please let me know.

Edit - a more detailed example:

Player is currently standing still.
User presses W to move the player up. This key is stored as the current movement key on a stack and as long as the key is pressed (checking per frame), the player will continue to move up.
User presses D to move the player right. The D key is stored as the current movement key on the same stack W was stored on. W is not the current movement key anymore.
User releases the W key - since this is stored on a stack, we know W was released but we cannot remove it from the stack (but we do know it is on the stack). I do not want to just keep adding the keys to the stack, thus the reason we check if the stack contains the key.
User presses the W key again. Since D is still the current movement key, and since we weren't able to remove W from the stack, we cannot add it to the stack again.


texts:
I'm drawing simple 2D line shapes using coordinate sets (for example, moveTo(x,y) drawTo(x,y)). I would like a tool that is like a sheet of graph paper.  When I click on intersection points it records the coordinates I clicked and prints them to a dialog box.

Hopefully it would be a simple website in javascript or something. Does such a thing exist?


texts: How do I reduce overdraw in a forest scene with lots of foliage?

texts:
Unity comes with an overdraw view that looks something like this:

We've probably all seen it, and have probably been advised to check for overdraw. How do you go about actually doing anything about it?

My specific case:

I'm currently seeing a lot of overdraw from my terrain grass and trees as they do not respect occlusion culling. This seems to be a limitation in Unity. Is there anything I could do about it to reduce overdraw without losing the lush environment?

For reference, here is the foilage responsible for most of the overdraw and I'm exploring options other than to simply reduce the amount of foliage in the scene and lose the aesthetics:


texts:
I'm wondering how to get all points (x,y) that constitute a given parabola.
It's barely to simulate a jump of an object from point A to point B.
I know:
-The coordinate of point A
-The coordinate of point B
-The coordinate of the parabola's top

What i'm trying to do is to loop from start_x to dest_x to calculate the Y-coordinate at that moment, but I don't know how to do that part.

pixels = []
for x in start_x to dest_x
   y = (calculate the Y-coord here based on x )
   pixels.push( [x,y] )
end
return pixels

My math skills are not exceptional.
Thank you.


texts: ADMOB: Why my match rate never increase?

texts:
I have a game deployed in the store, here are some app and admob metrics:

It makes ~120k requests per day
It have ~800 active devices in the last 30 days
It have less than 1% match rate(~0.3%)
Some math: 120k/0.8k(800) -> ~ 150 requests per user(really high I think)

I have read some articles and questions about this, what I did was:

Make sure to only request an ad when it needs to be displayed, I can't always ensure this, but I tried my best.
Make sure my app are not enrolled in the 'Designed for Families' program.
Make sure my ad content rating is for mature audiences(M).

All this was done last week, since then I have seen not a single change in the admob reports, everything stills the same, after changing the request rate I should have seen a decrease in the ad requests, it didn't happened, of course I'll wait more since only 400 active devices were updated with this new version(although I think it should have been reflected in the statistics already).
It is really frustrating, feels like I have no control over this, is there other reasons for admob to have low match rate? can someone help me here? Thanks all in advance.


texts: Trying to implement forward rendering in OpenGL

texts:
I'm working on implementing forward rendering in my 2D engine, as far as I'm aware everything should be set up correctly, I've ran into some issues earlier but I'm sure I've fixed those at this point.

So what I'm doing to achieve this (May or may not be the correct way of going about this) is that I'm rendering the object first with ambient light (Which works), and then for each light affecting the object, I render it once again using a different shader for point lights. I've set that shader to only output the color red atm, but nothing shows up apart from the first render of the object (The one with the ambient light).

Here are some pieces of my code.

Rendering of the object

        shader.Use();

        shader.SetUniform("_Model", transform.Model);
        shader.SetUniform("_Color", color.Normalized.ToVector3());
        shader.SetUniform("_Diffuse", texture.ArrayPos);

        VertexAttributePointer.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 5, (System.IntPtr)0);
        VertexAttributePointer.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 5, (System.IntPtr)(3 * sizeof(float)));

        //Render sprite
        quad.VAO.Bind();

        GL.Enable(EnableCap.Blend);

        //Transparency
        GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);

        //Draw object
        GL.DrawElements(PrimitiveType.Quads, 4, DrawElementsType.UnsignedInt, 0);

        //Forward rendering
        GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One);

        GL.DepthFunc(DepthFunction.Equal);
        GL.DepthMask(false);

        Shader pointLightShader = Shader.GetShader("Forward-Point");
        if (pointLightShader != null)
        {
            pointLightShader.Use();
            shader.SetUniform("_Model", transform.Model);
            shader.SetUniform("_Color", color.Normalized.ToVector3());
            shader.SetUniform("_Diffuse", texture.ArrayPos);

            foreach (Light l in Light.lights)
            {
                pointLightShader.SetUniform("_PointLight.position", new Vector3(l.position.X, l.position.Y, 0));
                pointLightShader.SetUniform("_PointLight.color", l.color.Normalized.ToVector3());

                GL.DrawElements(PrimitiveType.Quads, 4, DrawElementsType.UnsignedInt, 0);
            }
        }

        GL.DepthFunc(DepthFunction.Lequal);
        GL.DepthMask(true);
        GL.Disable(EnableCap.Blend);

        quad.VAO.Unbind();

        texture.Unbind();

Forward-Point fragment shader

Note that it is temporarily set to only output red, which should globally tint all objects if it works.

#version 330 core

struct Light {
    vec3 position;
    vec3 color;
};

uniform vec3 _CameraPos;
uniform vec3 _Color;
uniform sampler2D _Diffuse;
uniform Light _PointLight;

out vec4 color;
in vec2 TexCoords;
in vec3 FragPos;

void main()
{
    vec4 diffuse = texture(_Diffuse, TexCoords);

    float distance = length(_PointLight.position - FragPos);
    float attenuation = 1.0;

    vec3 finalLight = _PointLight.color * attenuation;

    color = vec4(1.0, 0.0, 0.0, 1.0);
}


texts:
I created a button class which draw a button on the screen. When I click on it, I want to see something happening. In WinForm, I would simply use the event OnClick of the button. What about XNA?

Should I add an OnClick event to my button class? Is that a good practice? Otherwise, how do you handle events in your game loop?


texts: How to modify normal vectors with a tranformation matrix

texts: Transformation is quite simple when it comes to Position or Color of the vertex, for Position just multiply matrix * vector and for color just don't do anything, but my question now is: How to handle normal vectors? If my thoughts are correct I would just need the rotation part of the matrix and apply it to the normal vectors, but how can I do that? Or is it better not to use a matrix for that, but instead allow only direct transformations, one at a time, so I can handle them differently for different vertex attributes?


texts: NodeJS client gameloop running slightly faster than server gameloop

texts:
So I'm working on a real time multiplayer game in NodeJs (Client and Server). Both loops handle the same "physics" (movement at a constant rate) and both are running at 40hz or 40 times per second. I am using setInterval on both client and server with a delay of 40ms. The issue is that my server average delta between each tick is ~41 and my client average delta between each tick is ~40. This leads to results like this:

See in the last result, there is a difference of 46 ticks meaning the client is rendering about 1.8 seconds ahead of server time. My first guess on solving this is to sync the client every so often but that would lead to it "teleporting" backwards quite often due to how much it is desyncing.


texts: How to create a standard pbr material with shader graph?

texts: I want to create a standard pbr material that is editable with the shader graph, but when I install the package and go the Create -> Shader tab, I only have 2 graph options:  Empty Shader Graph, and Sub Graph.  Isn't there a shader graph that starts me off with a basic pbr material with color and reflections?  I'm using unity 2020, and the default render pipeline.  Do I need to switch to ldrp or hdrp?


texts: Originating direction of shots in an FPS problem

texts:
Recently I have been asked on the interview about a maybe simple task to solve a problem.

We have a player, that looks in some direction, and a shooter, who already is shooting the player. I must find out whether the shots come from the left or right in the same way Counter Strike does when you get hit: the game shows from which direction and it looks like a red half-circle.

I know the vectors of players and enemies position. I tried different answers f.e. to build a line from the player see's and solve a linear system equation or rotate the player vector and then find out the angle of scalar product, but he says there's a better way to do it. I don't need the answer to this particular question, but a 'way' to find out the answer. F.e. any books related to this problems, some similar problems, etc.


texts:
I have been reading a lot of different shaders and some have the preference of:

sampler depthSampler : register(s1);

Whilst others take the longer route:

texture depthMap;
sampler depthSampler = sampler_state
{
    // etc.
};

Is there any real difference between the two?  Does one perform faster than the other?


texts: What metrics could be used to know what certain people think about the game and how much they liked it?  I would prefer parameters that don't need players to rate by themselves. Would hours of playing in a single seat be a good parameter about how much players wanted to spend time on game?


texts:
I'm trying to change the size of sprites in unity to fit the palette. Except there are no options to change multiple sprite sizes at once.

But when I watched a youtube video on tilemaps and palettes, there were options to change the size of the entire palette!

v2019.2.11f1 (Personal)


texts: How to rotate object just like in the scene?

texts:
Look at this image, I selected an object and pivot is set to local:

When I rotated selected object in the scene by X axis, it rotates exactly I wanted.

But if I rotate axis from inspector or script, it doesn't rotated to desired angle.

I'm not sure, but it seems it's related about Quaternion, but everything I tried doesn't worked well.

How do I rotate that object just like in rotated from scene?


texts: How do I make my SFML mouse position capture fast enough?

texts:
I'm new to game development and making a Pong clone in SFML. I am trying to set the screen's top and bottom as bounds for the paddle.

Here is my attempt:

#include "main.h"
#include "objects.h"

int main()
{
sf::RenderWindow window(sf::VideoMode(900, 600), "Pong");
window.setVerticalSyncEnabled(true);
initData();
while (window.isOpen())
{
#pragma region Event Handling
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type)
        {
        case sf::Event::Closed:
            window.close();
            break;
        default:
            break;
        }
    if (sf::Mouse::getPosition(window).y <= 500 &&  sf::Mouse::getPosition(window).y >= 0)
    {
        player1paddle.setPosition(100, sf::Mouse::getPosition(window).y);
    }
    }
 #pragma endregion
 #pragma region Rendering
    window.clear(sf::Color::Black);
    window.draw(net);
    window.draw(player1paddle);
    window.draw(aipaddle);
    window.display();
 #pragma endregion
}

    return 0;
}

The problem: When I move the mouse fast, the sprite stops moving before it hits the bottom. I'm assuming this is caused by the mouse moving faster than the loop is running. Is there a faster/more efficient way to do this?


texts: Rotating a vector by another vector in shader

texts:
I have a terrain surface with a normal for each point on the terrain.

I have a second detail normal map to be applied to the terrain.

These normals are in 3-space.
The Y value of both normals is
always positive.
The X,Z values of both normals can be
positive/negative/zero.
The 1st normal vector (blue) that we are rotating the 2nd vector (orange) by, can be almost horizontal.

I am okay with an approximate solution if it makes it easier/faster to compute.

In the above image, you see the blue surface normal (from the 1st normal map),  the orange normal map normal (from the 2nd normal map), and the green desired result normal.

The amount that the orange vector is rotated should be roughly (or if possibly exactly) equal to the angle that the blue normal vector forms with the XZ plane (where Y is up, like the DirectX coordinate system).

Here is a second scenario:

In the above image, the blue surface normal is almost horizontal, so the 2nd normal map is being applied to an almost vertical surface, thus the orange normal map vector is rotated further.

The rotation is being implemented in a HLSL shader.

How do I rotate the 1st orange normal based on the direction of the 2nd blue normal?

Edit: Maybe I need a tangent and bitangent as well as the normal?

Here's how I get the normal:

float4 ComputeNormals(VS_OUTPUT input) : COLOR
{
    float2 uv = input.TexCoord;

    // top left, left, bottom left, top, bottom, top right, right, bottom right
    float tl = abs(tex2D(HeightSampler, uv + TexelSize * float2(-1, -1)).x);
    float  l = abs(tex2D(HeightSampler, uv + TexelSize * float2(-1,  0)).x);
    float bl = abs(tex2D(HeightSampler, uv + TexelSize * float2(-1,  1)).x);
    float  t = abs(tex2D(HeightSampler, uv + TexelSize * float2( 0, -1)).x);
    float  b = abs(tex2D(HeightSampler, uv + TexelSize * float2( 0,  1)).x);
    float tr = abs(tex2D(HeightSampler, uv + TexelSize * float2( 1, -1)).x);
    float  r = abs(tex2D(HeightSampler, uv + TexelSize * float2( 1,  0)).x);
    float br = abs(tex2D(HeightSampler, uv + TexelSize * float2( 1,  1)).x);

    // Compute dx using Sobel filter.
    //           -1  0  1
    //           -2  0  2
    //           -1  0  1
    float dX = tr + 2*r + br - tl - 2*l - bl;

    // Compute dy using Sobel filter.
    //           -1 -2 -1
    //            0  0  0
    //            1  2  1
    float dY = bl + 2*b + br - tl - 2*t - tr;

    // Compute cross-product and renormalize
    float3 N = normalize(float3(-dX, NormalStrength, -dY));

    // Map [-1.0 , 1.0] to [0.0 , 1.0];
    return float4(N * 0.5f + 0.5f, 1.0f);
}

How might I get the tangent and bitangent vectors then?

Is it enough to take the cross product of the normal with the Z axis unit vector to find the tangent vector? (Since the normal.Y is always positive, where Y is up, and Z is pointing into your screen).

And then take that tangent vector and cross it with the normal to obtain the bitangent?

And then take the normal, tangent and bitangent together to form a rotation matrix to rotate the orange normal map vector?

Even if that works, this seems like a lot of computation for a pixel shader. Does this work, and is there a more efficient way?

Edit:

This image may help you understand what I'm trying to do:

If you know what normal mapping is, then this should be straightforward, I think.

I'm trying to take the normal map, which contains various normals, and apply them to a surface. The surface has it's own normals. The normal map will contain many more normals than the surface, so several normal map normals are sampled across a single part of the surface that has only a single normal.


texts: Can't find sibling node, keeps giving "null instance"

texts:
I'm trying to set it up so that there are three buttons but only one can be toggled at a time. So when one button gets toggled it makes sure that the other two are not toggled.

The code is trying to set the toggled status however since it can't find the node I'm at a loss.

var vec = Vector2(0,1000)
var ori = Vector2(0,0)
func _ready():
    pass

func _on_Ally1_Button_toggled(button_pressed):
    if button_pressed:
        set_position(ori)
        $Player_Button.set_pressed(false)
    else:
        set_position(vec)

This is what the tree looks like.

The Player_Ally1_ui is trying to access Player_Button but as stated it can't seem to find it and just returns null.

Any help is greatly appreciated, thank you in advance.


texts: The import aurelienribon cannot be resolved

texts:
I've been having problems with using the Tween Engine by aurelien ribon for a Splash Screen for my 2d game. I'm using Eclipse and libgdx.

I've tried rebuilding, clean...-ing, and refreshing.

I've closely followed the import directions from here:
https://github.com/libgdx/libgdx/wiki/Universal-Tween-Engine

I'd be more than happy to provide anyone with more information/code if they need it.

The import file/lines of code (Game Renderer class):

package com.companyname.gameWorld;

import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.TweenManager;

build.gradle:

project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"

        compile "com.badlogicgames.gdx:gdx-bullet:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-x86"

        compile fileTree(dir: '../libs', include: '*.jar')
    }
}

...(other project(":...")s)...

project(":core") {
    apply plugin: "java"

    dependencies {
        compile "com.badlogicgames.gdx:gdx:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"

        compile "com.badlogicgames.gdx:gdx-bullet:$gdxVersion"

        compile fileTree(dir: '../libs', include: '*.jar')
    }
}

The /libs folder:


texts: How can I compile and distribute a Torque2D game as an executable?

texts:
Is it possible to compile a Torque2D into a executable rather than having to run Torque2D.exe from the project folder (where all the modules and  artwork are)?

What would be the normal procedure to distribute a game written with Torque2D?


texts: 2D tilemap editor UI--how do I disable editing while save/load dialog is open?

texts:
I'm working on a basic 2D tilemap editor in C#/XNA. Currently, it displays the map through a picturebox through which XNA's output is being routed, and editing is accomplished through simply checking mouse position (i.e., Is it within the picture box? If so, what tile is it on?).

The problem I'm having is that this results in the map being edited through other windows. For example, when trying to save a map, any clicks in the savefiledialog window will edit the map square beneath it, including the click on "Ok" or "cancel."

I believe this is the offending snippet of code from the Game1 class:

protected override void Update(GameTime gameTime)
    {

        Camera.Position = new Vector2(hscroll.Value, vscroll.Value);

        MouseState ms = Mouse.GetState();

        if ((ms.X > 0) && (ms.Y > 0) &&
            (ms.X < Camera.ViewPortWidth) &&
            (ms.Y < Camera.ViewPortHeight))
        {
            Vector2 mouseLoc = Camera.ScreenToWorld(
                new Vector2(ms.X, ms.Y));

            if (Camera.WorldRectangle.Contains(
                (int)mouseLoc.X, (int)mouseLoc.Y)) //<--right there
            {
                if (ms.LeftButton == ButtonState.Pressed)
                  //....

Two questions.

Is this even a viable way to display the map in the map editor? I'd like to be able to pan, zoom, etc. in the future, as well as select multiple tiles at once and edit their properties.
How do I stop the picturebox from registering clicks while other windows are in focus? I've tried adding && PictureBox.Focused to the if statement up there, but that stops it from accepting input at all, regardless of whether there's another window over it (apparently, "focus" doesn't mean what I thought it meant in this context).

Confession: this is my first attempt at Winform programming. Please excuse my lack of experience.

UPDATE: && pictureBox.Focused didn't work, but && pictureBox.Capture did. Still feels a little sloppy, but it works now. I have no confidence that this solution is correct, so I'm not closing the question just yet--something tells me there's a more correct way, and I'd like to know about it.

UPDATE2: Using Capture has introduced a new bug--right clicks don't register reliably (i.e., only around one in ten clicks) until minimizing and restoring the window, after which they register correctly. Rage.


texts:
I would like to make a trail for a pixelated snake such as this one :

As you can see, the cross simply repeats itself to create the snake. In Unity I have messed around with Trail Renderer, tried everything to import the cross as a texture / sprite, then created all sorts of materials for it, but it just won't work the same way.

How can I achieve this effect please? Thanks!


texts:
I have a simple code written in Processing 3.x that I am using to test out the collision detection for a cave/maze.

The code is here: https://github.com/NoahJon3s/New-Journey-The-Game/blob/master/sketch_190820a.pde

If you where to run said code, you'd see that I have the code so that it detects collisions on the x-axis (top of the rectangle) and y-axis (left side of the rectangle), and correctly prevents the movement of the "player" from moving out of the rectangle, but I cannot seem to find a solution for preventing the movement out of the bottom or the right side of the rectangle, even though I am able to detect the collision. Every solution I try seems to lock the "player" to those respective sides. Any suggestions?

Thanks in advance.


texts: What is the difference between static meshes and regular 3D models. I am very new to game development, and I am using UDK (Unreal Development Kit).


texts: Project location to perspective fake 3D view

texts:
I am trying to implement a perspective view in a 2D soccer game, such like Nintendo World Cup. In this case, the soccer pitch will look like a isosceles trapezoid, but not a rectangle in real.

Here is my solution:

I separate the game logic location and the final rendering location. In the game logic part, the pitch is still a rectangle, so we can make easy collision detection, player area change, out-of-bound checks, goal check, etc.. Just like an answer to Stack Overflow question Implement a projectile motion and collision detection - response in a 2D top-down game said:
Then I just project players', ball's location into final screen location, so that player can fit in pitch (because the exact pitch image is a trapezoid like the screenshot)

I tried to do like that post said, but the result is wired, so I am thinking do I need to make a perspective projection like in a 3D game, but I do not know how. A 3D perspective projection needs to know the camera position, camera angle, near plane, but these do not exist in a 2D game.

How do I solve this problem?


texts:
A bitmapfont consists of a image and a textfile that hold the position and size of each character on that image. Is there any way to create the text file with just a image? Or do I have to manually create the "atlas" for each character, which is kinda tedious.

Here is a line for a character in such a textfile .fnt

char id=36   x=0     y=0     width=46     height=83     xoffset=1     yoffset=0    xadvance=51     page=0  chnl=0

I think xadvance would mean how many pixels to advance on the line to put the next character. I have 36 characters A-Z0-9 but I want upper and lower case to output the same image.

I need this specifically for libgdx but this would probably be the same for any tool that uses a BitmapFont.

In addition I have a xml file that came with the sheet that includes the characters allong with the other images.

<TextureAtlas imagePath="sheet.png">
  ...
  <SubTexture name="letterA.png" x="412" y="835" width="61" height="64"/>
  <SubTexture name="letterB.png" x="460" y="977" width="52" height="66"/>
  <SubTexture name="letterC.png" x="432" y="1613" width="54" height="66"/>
  ...
</TextureAtlas>

I also have a each character separately in PNG and Vector.

To make clear to what I need this is a complete .fnt it needs to be accompanied by a single image that holds all the images of each character.

info face="FontName" size=78 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=0,0
common lineHeight=93 base=73 scaleW=512 scaleH=512 pages=1 packed=0
page id=0 file="fontsheet.png"
chars count=83
char id=32   x=0     y=0     width=0     height=0     xoffset=0     yoffset=73    xadvance=25     page=0  chnl=0
char id=36   x=0     y=0     width=46     height=83     xoffset=1     yoffset=0    xadvance=51     page=0  chnl=0
char id=106   x=46     y=0     width=19     height=82     xoffset=2     yoffset=9    xadvance=26     page=0  chnl=0
char id=41   x=65     y=0     width=20     height=75     xoffset=1     yoffset=3    xadvance=26     page=0  chnl=0
char id=40   x=85     y=0     width=21     height=75     xoffset=2     yoffset=3    xadvance=27     page=0  chnl=0
char id=96   x=106     y=0     width=31     height=75     xoffset=5     yoffset=0    xadvance=39     page=0  chnl=0
char id=64   x=137     y=0     width=72     height=68     xoffset=1     yoffset=7    xadvance=77     page=0  chnl=0
char id=48   x=209     y=0     width=51     height=68     xoffset=1     yoffset=7    xadvance=57     page=0  chnl=0
char id=85   x=260     y=0     width=54     height=68     xoffset=1     yoffset=7    xadvance=60     page=0  chnl=0
char id=79   x=314     y=0     width=60     height=68     xoffset=1     yoffset=7    xadvance=65     page=0  chnl=0
char id=38   x=374     y=0     width=60     height=67     xoffset=2     yoffset=8    xadvance=65     page=0  chnl=0
char id=54   x=434     y=0     width=47     height=67     xoffset=1     yoffset=8    xadvance=53     page=0  chnl=0
char id=121   x=0     y=83     width=43     height=67     xoffset=1     yoffset=26    xadvance=48     page=0  chnl=0
char id=113   x=43     y=83     width=48     height=67     xoffset=1     yoffset=24    xadvance=53     page=0  chnl=0
char id=112   x=91     y=83     width=48     height=67     xoffset=0
// etc...


texts: web based networked game physics efficiency

texts:
I am writing a web based game, using websockets. its pretty simple, two players shooting at each other with bullets that have acceleration from a starting point at an angle.

The client side (frontend in web dev terms) uses phaser.io with p2js for physics.

However after reading this post, i believe that it's smarter to do some of the physics for the players on the server side. Such as collision detections, and update the player positions at regular intervals to keep the two players at sync.

Now i have two questions

if i use the Box2d javascript port on nodejs on the server side to simulate server side physics, than is it just as efficient as using the native c++ one? seeing as from what i have read so far it seems the js ports aren't that well maintained, and they are js ported - on the other hand the js codes might be easier to deal with than the c++ ones.
using p2js on the client side and using box2d on the server. The server being authoritative, and sends regular updates (once every second) as to the actual positions of the players.  will the physics simulation be in sync (atleast to the user)? Theoretically i don't see any reason for it to not, given that both user has the exact same latency (this is assumed for sake of simplicity).


texts:
I have (methink) a simple question regarding attaching scripts to a GameObject.
Is there any performance loss if I attach a script to a GameObject for each action to be performed (such as movement, attaking, interacting) instead of attaching a single script dealing with every single aspect?

I'd like to separete these things due to clearity reasons but I wonder if calling different FixedUpdate() functions would imply some kind of issue. For example: is their execution ensured to be called sequentially or they could run asincronously?


texts: Best way to draw a textfield in OpenGL, when performance really matters?

texts:
I'am creating my own GUI library in LWJGL (opengl for Java).
I already managed in creating buttons and panels, and I've also got the hover and active states of the components implemented. This question is about finding a fast way to render a complex component.
The library should be very performant!

So I pre-render everything I can, before the gameloop starts.
I also want to decrease the use of VBO's, triangles, and textures to render a single component.
My approach for creating a button is: pre-render the button appearance using a java Graphics object and put the drawing in a Power Of Two sized BufferedImage. That image is the texture.

Then I've got a FilledRectangle class. That class gets a BufferedImage (the texture) and an x, y, width and height. The class creates a VBO that just renders the Button.
For the hover state and active state, I really do the exact same thing, except that there is another drawing made with the Graphics object. So I just create another VBO for each state.

When it comes to rendering components that change their appearance, I can't pre-render too much.
I want to create a TextField.
Now I pre-render the background (the box of the textfield).
And I also pre-render the cursor.
The text has to be rendered during the game, and I have the following options:

Rendering the text using a Graphics object from the java graphics.
Pre-render a spritesheet (a character map) with all characters on it in a specific font, and then use that texture to create a new VBO for every time the text changes.
Note that the box of the component and the cursor are seperate VBO's so, when the text changes, I only have to deal with text rendering in a fast way.

My questions

It's very easy for me to draw things using a java Graphics object, but isn't this too slow when I have to use this during the gameloop?
Is it OK to recreate a VBO for every visible change?


texts: Finding equivalent axial coordinates for a wrapping hexagonal map of radius n

texts:
I'm creating a wrap around hexagonal map that will potentially render infinatly.

With the method I'm using, I have an x-y coordinate I use to find it's equivalent axial coordinate with the equations:
Q = (sqrt(3)/3 * x - 1./3 * y) / hexSize;
R = (2./3 * y) / hexSize;
the problem is, my map is of radius n and it's possible for the Q R coordinate to be far outside that radius. How can I find the equivalent Q-R coordinate within the radius n? I know methods for a single radius outside, but I'm talking the potential of having a radius of 15 but a Q-R something like (9999999,99999999). What would that coordinate be in relation to the center of the 15 radius hex region it'd be in?


texts: How to convert OpenCV camera capture to Irrlicht texture without killing fps?

texts:
I am looking to include images captured from the users webcam into my application so I've been looking into using OpenCV to capture from the webcam and then render it in Irrlicht. I've created a basic app to test and I'm doing this in my main loop to capture and convert to ITexture* to render onto a cube.

    if( cv::waitKey(50) >= 0 ) break;
    capture >> camera_frame;

    if( ! camera_frame.empty() )
    {
        unsigned char *tex_buf = (unsigned char*)frame_tex->lock();
        unsigned char *frame_buf = camera_frame.data;
        // Convert from RGB to RGBA
        for(int y=0; y < camera_frame.rows; y++) {
            for(int x=0; x < camera_frame.cols; x++) {
                *(tex_buf++) = *(frame_buf++);
                *(tex_buf++) = *(frame_buf++);
                *(tex_buf++) = *(frame_buf++);
                *(tex_buf++) = 255;
            }
        }
        frame_tex->unlock();

        //cube->setMaterialTexture(0, driver->getTexture("../../media/t351sml.jpg"));
        cube->setMaterialTexture(0, frame_tex);
        cube->setMaterialFlag(video::EMF_LIGHTING, false);

    }

...

It works.... BUT... the framerate drops to about 4fps.

Yes, it probably could have been done slightly more efficiently, but it's a massive drop in framerate for something so simple.

Is there another way to do this that won't kill the framerate?


texts: Why are most windowed games not resizeable?

texts:
I find it incredibly rare to find a game where the window can be resized, even if permitting it is a single click away in their game engine. For what reason is this done?

Thoughts that come to mind are...

Performance, is it possible that certain resolutions still perform better in windowed mode?
Easy switching to fullscreen, as fullscreen usually requires supported resolutions. However, I find even borderless fullscreen games still prevent resizing.
Management of aspect ratios? I don't think this would be a big issue to overcome however.

There's so many games that I want to be able to resize so I can fit them where I want on my screen, but alas, it's rare.


texts:
I have already done this:

Unity3D > Edit > Project Settings > Player

Scripting Runtime Version: Experimental (.NET 4.6 Equivalent)
Api Compability Level: .NET 4.6

Visual Studio > Tools > Options > Tools for Unity

Access to project properties: true

Visual Studio > Project > Properties

Application > Target Framework: .NET Framework 4.6.2
Build > Advanced > Language Version: C# 6.0
then save

After this: every error disappears that were there due to using new stuff.

But:

As soon as Unity3D does something referencing something in VS, the Project Settings go back to the old one.

For example:

I delete a .cs file in Unity3D, then I switch back to VS. It says that the Project was changed outside, so I have to reload it. After reloading, the settings are reverted.
I double click on a .cs file in Unity3D because I would like to open it in VS. Unity3D switches to VS for me and after that the project settings are reverted.

Etc.

The code compiles in Unity3D, everything is fine but everytime I use something new one new error will pop up in the error list which is a bit distracting.

Question:

How can I disable this reverting?
Or how can I supress these errors?


texts: Box2D body jitters when colliding with static body

texts:
I am developing a game where a body is moved within the scene using touch. The scene has a boundary wall made up of static rectangular bodies. When I move the object along the boundaries, on collision, it jitters.

This is because the boundary wall pushes the body outwards while the touch pushes it against the wall. I am using linear velocity to move the body using touch. I tried to avoid this by setting the linear velocity of the body to 0 on collision with the boundary wall but it didn't work. I am trying to have a smooth movement along the boundary walls with no jitters. How can I solve this?

Following snippet moves the body on touch. Linear velocity vector has direction towards the touch point. The movement is smooth within the play area but not at the boundaries.

 case TouchEvent.ACTION_MOVE:

                strikerBody.setLinearVelocity((pSceneTouchEvent.getX()-body.getPosition().x * PIXEL_TO_METER_RATIO_DEFAULT),(pSceneTouchEvent.getY()-body.getPosition().y * PIXEL_TO_METER_RATIO_DEFAULT));

These are the bounadry walls:

final Rectangle groundLeft = new Rectangle(camera.getWidth() / 2 - camera.getWidth() / 4, 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);
        final Rectangle groundRight = new Rectangle(camera.getWidth() / 2 + camera.getWidth() / 4, 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);

    final Rectangle roofLeft = new Rectangle(camera.getWidth() / 2 - camera.getWidth() / 4, camera.getHeight() - 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);
    final Rectangle roofRight = new Rectangle(camera.getWidth() / 2 + camera.getWidth() / 4, camera.getHeight() - 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);

    final Rectangle leftTop = new Rectangle(1, camera.getHeight() / 2  + camera.getHeight() / 4 + camera.getHeight() / 12 + camera.getHeight() / 16 , 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);
    final Rectangle leftBottom = new Rectangle(1, camera.getHeight() / 2  - camera.getHeight() / 4 - camera.getHeight() / 12 - camera.getHeight() / 16, 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);

    final Rectangle rightTop = new Rectangle(camera.getWidth() - 1, camera.getHeight() / 2  + camera.getHeight() / 4 + camera.getHeight() / 12 + camera.getHeight() / 16, 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);
    final Rectangle rightBottom = new Rectangle(camera.getWidth() - 1, camera.getHeight() / 2  - camera.getHeight() / 4 - camera.getHeight() / 12 - camera.getHeight() / 16, 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, groundLeft, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, groundRight, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    PhysicsFactory.createBoxBody(this.mPhysicsWorld, roofLeft, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, roofRight, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftTop, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftBottom, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightTop, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightBottom, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    this.attachChild(groundLeft);
    this.attachChild(groundRight);
    this.attachChild(roofLeft);
    this.attachChild(roofRight);
    this.attachChild(leftTop);
    this.attachChild(leftBottom);
    this.attachChild(rightTop);
    this.attachChild(rightBottom);


texts:
I have been around programming for a while as a hobby, but I did not start seeing this concept until recently. I have google'd "what is serialization" numerous times, but I never actually get any sort of definition, usually just examples of how to do it. I am seeing it around the Ogre forums, the Bullet forums, and every other forum I go to, so I think it is about time I actually understand what it is, and why to use it.

Edit

To clarify, I am looking more for why to use it, especially in the sense of game programming. For example, the Bullet Physics API talks a lot about serializing a mesh, so I want to understand why that is.

Thank you :)


texts:
I've created an animation to animate a swinging mace.

To do this I select the mace object in the scene pane, open the animation pane, and key it at a certain position at 0:00.

I'm prompted to save this animation in my assets folder, which I do, as maceswing

I then rotate the mace, move the slider through time and key it in a different position. I move the slider through time again, move the object to the original position and key it.

There are now three things in my assets folder:

maceswing appears to be my animation, but I have no idea what Mace Mace 1 and Mace 2 are. (I've been mucking around trying to get this working so it's possible Mace 1 and Mace 2 are just duplicates of Mace. I still want to know what they are though)

When I play my game, the mace is constantly swinging, even though I didn't apply maceswing to it. I can't stop it. People say there's some kind of tick box to stop it constantly animating but I can't find it.

My mace object only has an Animator component:

Unticking this component doesn't stop the animation playing so I have no idea where the animation is coming from. Or what the Animator component actually does.

I don't want this animation constantly playing. I only want it to play once when someone clicks a certain button:

var Mace : Transform;
if(Input.GetButtonDown('Fire1')){
    Mace.animation.Play('maceswing');
};

Upon clicking the 'Fire1' button, I get this error:

MissingComponentException: There is no 'Animation' attached to the "Mace" game object, but a script is trying to access it.
You probably need to add a Animation to the game object "Mace". Or your script needs to check if the component is attached before using it.

There is no 'Animation' attached to the "Mace" game object, and yet I can see it swinging away constantly. Infact I can't stop it! So what's causing the animation if the game object doesn't have an 'Animation' attached to it?

My maceswing animation object:


texts:
I use a deferred rendering. During g-buffer stage my rendering loop for a sponza model (obj format) looks like this:

int i = 0;
int sum  = 0;
map<string, mtlItem *>::const_iterator itrEnd = mtl.getIteratorEnd();
for(map<string, mtlItem *>::const_iterator itr = mtl.getIteratorBegin(); itr != itrEnd; ++itr)
{
   glActiveTexture(GL_TEXTURE0 + 0);
   glBindTexture(GL_TEXTURE_2D, itr->second->map_KdId);
   glDrawElements(GL_TRIANGLES, indicesCount[i], GL_UNSIGNED_INT, (GLvoid*)(sum * 4));
   sum += indicesCount[i];
   ++i;
   glBindTexture(GL_TEXTURE_2D, 0);
}

I sorted faces based on materials. I switch only a diffuse texture but I can place there more material properties. Is it a good approach ? I also wonder how to handle a different kind of materials, for example: some material use a normal map, other doesn't use. Should I have a different shaders for them ?


texts:
I know we need to add rigidbody if we are moving objects.In Unity 5 the performance of moving non rigidbody objects has been increased too.

Though I have doubt over ,Do I need to add rigidbody if I am animating only UVs without moving the object?


texts:
I'm making a game and I'm struggling with the formula to calculate the real damage the player does. I have skills which can do for example 10 hits of 20% weapon damage each of a total of 200% damage. Or another skill does 200% damage 1 hit.

However the formula I have right now is something like this

( 2 * Attack - Defense ) * 0.5

As you can see with an equal defense, the attack that does 1 hit 200% weapon damage will actually do more damage than the skill that does 10 hits 20% weapon damage each, because the reduction is greater when dealing low amounts of damage.

Or another case is a weapon does 200 physical damage and 50 fire damage. With this formula a enemy with 100 defense receives 150 physical (ok) and 0 fire damage (negative, not ok)

Can anyone help me get a formula (not too complex)? I don't know what to try. What I want to achieve is to get the same real damage (1 hit @ 200% or 10 hits @ 20%) and make the defense matter, what I mean by that is that it affects the attack.


texts: How do I associate my objects to my meshes and other resources?

texts:
I am creating a simple 3D engine and I've run into a problem.

I have an array of objects

[Camera, Player, Player, MonsterA, MonsterB, MonsterA]

and a number of mesh files that I need to associate with these game objects

camera.obj, male.obj, female.obj, etc.

I pass the state of the world (the array of objects) to my renderer, and I would like to render each object with its associated mesh.

My question is: how / where do I tie these game objects to their meshes?

Should I keep them together as game objects?

eg. [(Camera, camera.obj), (Player, male.obj), ...]

Or should I have some sort of associative structure within my renderer? Or somewhere else entirely? This question also applies to textures as well. Basically, how do I connect the game objects to their assets?


texts:
I have two kinematic rigidbody cubes from the standard 3D objects, I have also enabled contact pairs mode to "all contact pairs", how do I make it so that no matter what angle they collide in they perserve the same angle but just get out of each others space making it look like they're in contact e.g. collided?
Here is my attempt at doing that:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

 public class Physics : MonoBehaviour
{
  private Collider collider1;
  private bool grounded = false; //used to determine if the collider hit something so it doesnt keep going down

// Start is called before the first frame update
void Start()
{
    collider1 = GetComponent <Collider>();
}

// Update is called once per frame
void Update()
{
    if (!grounded) //if the collider hit something, stop going down
    {
        collider1.transform.Translate(0f,-.1f,0f,Space.World);

    }
}

private void OnCollisionEnter(Collision collision)
{
    grounded = true; //the collider hit something
    if(collider1.transform.position.y != collider1.bounds.extents.y) //if this is true, it means it is at the floor so dont move it
    {
        transform.position = new Vector3(collider1.transform.position.x, collision.collider.bounds.size.y + collider1.bounds.extents.y, collider1.transform.position.z); //attempts to put the collider on top of whatever it get

    }

 }

}

This works if the cubes are right on top of each other with no angle:

It also works if one of the cubes collides at a angle to the other cube, when they collide the bottom cube perverse its angle of collision and and the top cube just gets out of the space of the other collider making it look like they have collided:

What doesn't seem to work is if both cubes collide with each other at a angle, although they preserve their angle of collision, and also get out of each others space, they do not remain in contact with each other which if they did would make it look like they have collided.

Instead there is a gap between them, how do I get rid of the gap e.g. make it so that no matter what angle the objects are at they get out of each others space, preserve the angle, and remain in contact with each other to give the illusion that they have collided?


texts: Designing rules to fight smallpox in Civ-style TBS games

texts:
TL;DR: How do you design a ruleset for a Civ-style TBS game that prevents city smallpox from being a profitable or viable strategy?

Long version: Civ-style games are pretty great. Bringing a civilization from cradle to grave is a great endeavor, and practicing diplomacy with hard-line human players is fun and challenging. In theory.

In practice, however, many of these games has, especially in multiplayer, exactly one viable strategy: City smallpox, a.k.a. infinite city spread, a.k.a. covering all available space with 1-citizen cities, packed as tight as they will go. I suppose this could count as emergent gameplay, but still; it could hardly be considered to be in the spirit of the class of game.

The Civilization series, of course, is stuck in their more or less fixed rule sets, established with Civilization. Yes, there have been major changes in some respects, but the rules pertaining to city building and maintenance have stayed pretty similar.

So the question, then: If you build a ruleset for a TBS from the ground up; what rules should be in place to prevent Infinite City Sprawl from being a viable strategy?

Or should ICS be a viable strategy?


texts:
I wanted to try rendering to multiple render targets as a first step to deferred shading, but I'm getting somewhat peculiar behavior where the contents of all render targets are the same as the first one.

So far all the render targets have the same format.

The relevant snippets from the shaders are:

//geometry rendering
struct PS_OUT {
    float4 diff : SV_TARGET0;
    float4 norm : SV_TARGET1;
    float4 spec : SV_TARGET2;
    float4 uv   : SV_TARGET3;
};

PS_OUT PS(PS_IN input)
{
    PS_OUT output;
    output.diff = mytexture.Sample(mysampler, input.uv);
    output.norm = input.normal;
    output.spec = float4(input.pos.xyz, 1);
    output.uv = float4(input.uv, 0, 1);
    return output;
}

//"compositing" with fullscreen quad
Texture2D diff;
Texture2D norm;
Texture2D spec;
Texture2D uv;
SamplerState mysampler;

PS_IN VS(VS_IN input)
{
    PS_IN output ;
    output.pos = float4(input.pos,1);
    output.uv = float4(input.uv, 1, 1);
    return output;
}

float4 PS(PS_IN input) : SV_TARGET
{
    float4 diffuse = diff.Sample(mysampler, input.uv.xy);
    float4 normal = norm.Sample(mysampler, input.uv.xy);
    float4 specular = spec.Sample(mysampler, input.uv.xy);
    float4 uvw = uv.Sample(mysampler, input.uv.xy);

    return normal;
}

Sorry for the long post.

Now, the weird part is, if I return any of the sampled colors alone, like for example the normal, the first G-Buffer "channel" gets drawn to the screen instead. (Even if the normal channel is the only one I sample).

However, if I return this instead: 0.0001*diffuse + 1.0*normal + 0.0001*specular + 0.0001*uvw then it does return the actual normal channel.

This 0.000*diffuse + 1.0*normal + 0.000*specular + 0.000*uvw however results in just the diffuse being drawn again.

There are no Info or Warning or Error messages from the debug layer, turning the debug layer off doesn't change anything either.

Could the HLSL compiler possibly be optimizing the Sample calls away since the result is not used, and then removing the texture objects alltogether since they are not sampled from?

PS, if you think seeing how I create and assign the render targets etc will help, I will add it. I just didn't want to make the post any longer.


texts: Unity WebGL: how to copy to clipboard text from an inputField?

texts:
I would like to know if there is a solution to copy/paste the text from/to an InputField  in a WebGl Unity app.
Edit: for security reason, Unity WebGL doesn't allow text copy and paste in/from browser.
Thanks


texts:
First, here's the link to the actual article that describes CMAA and how to do it.
https://software.intel.com/en-us/articles/conservative-morphological-anti-aliasing-cmaa-update

My problem is that I can barely understand the steps involved. Either the wording is bad or my reading comprehension is bad, English not being my native language.

Could someone put it in simpler terms (Or maybe pseudocode if it's easier for you) so I can understand and implement it?

Specifically the steps 1 through 4.


texts: How to move the camera in XNA only after few moments?

texts: I made the camera position 10 units from an object, but not behind it. I dont want the camera position behind the object right away when it rotates, I want that when I will rotate the object, the camera position will move slowly until it will be behind the object.


texts: Where can I find a service hosting tournaments with prize funds?

texts:
I have a game, and users are self-organizing to create tournament sites. They want to be able to create a tournament, have competitors put down a $1 each, and the winner takes all.

Are there any companies that provide a service like this that I could integrate into my game directly? Or do people usually build this themselves into their games? I don't really want to deal with maintaining escrow accounts and all that myself.


texts: I have a third party package that is for mobile VR. it consist of two cameras that giving me the feel of VR Look. I have designe a user interface which i want to show from my both VR cameras but the problem both camera showing single UI. My UI not duplicating for each camera instead its only showing single UI as image depicted. How can i duplicate My UI so that it show from both VR cams


texts: How do I autogenerate gradient lighting?

texts:
I am trying to think of a way to generate a gradient like this picture:

Something like this GetGradientTexture(360f,100(width),100(height)), or if i want a directional light (like a flashlight) 180f,10,200.

But I can't really think of a good way to do this. Does anyone have anything that can push me in the right direction?


texts: In Godot browser game, is it possible to let the player download a file?

texts: I have a Godot game exported to the browser. I want to let the player export some data and let it save the data as a file on their PC, as if they were downloading a file from the Web. Is it possible for me to do that?


texts: What is the simplest way to rotate a 3D point arohnd another point given a quaternion?

texts:
I am weak in understanding quaternions however I am learning. Right now, I know how to rotate a point around another point given an angle represented by a Vector3 using a rotation matrix.
However because of order of rotations this causes undesirable behaviour for me. I need to understand how I can rotate a point around another point with a quaternion.
For context, I am getting the rotated vertices of an oriented bounding box.


texts: Exact collision detection for high-detail deformable triangular meshes

texts:
What robust methods or approaches exist for exact collision detection involving high-detail, deformable geometry?

The kind of mesh I am describing is a surface that is specified as a triangulated polyhedron and looks very similar to this:

For the specific application I am working on, I need to find all the contact points for colliding meshes that undergo subsequent deformation. Possible deformations that may occur during a collisional event:

1) the mesh decomposes, or fragments into smaller (triangulated) meshes

2) the mesh retains integrity but the vertex values of it's surface change

3) both of the above deformations occur

There is no real-time constraint; accuracy rather than performance is the critical factor.