texts: [SyncVar]s in Unity with client authority

texts:
I'm making an networked RTS in Unity, and I have a problem with syncing a boolean on a non-player object. I create the object (which is a boat) using SpawnWithClientAuthority() on the server, with the boat's owner as the player argument.

From my knowledge of SpawnWithClientAuthority(), it would seem that I could then change the boat's SyncVars from the client and they would be reflected on other clients, but this doesn't seem to be the case. I do have Local Player Authority checked on the boat's NetworkIdentity. What's even more interesting is that the change works if it occurs on the Host's client, whereas it doesn't if it's on the remote client.


texts: How do I trigger OnSelect() via the ISelectHandler in my class?

texts:
I'm trying to figure out how I can make a custom UI element identify when it has been selected or deselected. Classes such as Selectable inherit from the ISelectHandler and IDeselectHandler  and their methods OnSelect() and OnDeselect() are called whenever I click inside the Selectable element and click outside of it.

From my understanding, inheriting from the appropriate handler interface and implementing it's required method will allow your class to handle events from the EventSystem. As an example if I have:

public class TestSelectable
    : MaskableGraphic,
    ISelectHandler,
    IDeselectHandler,
    IPointerEnterHandler,
    IPointerExitHandler
{

    public void OnSelect(BaseEventData eventData)
    {
        Debug.Log("Selected");
    }

    public void OnDeselect(BaseEventData eventData)
    {
        Debug.Log("De-Selected");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Pointer Enter");

    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Pointer Exit");

    }

When the mouse enters and exits the element the OnPointerEnter() and OnPointerExit() methods are sucessfully called. However selecting/De-selecting the element does not cause the OnSelect() or OnDeselect() methods to be called. Though if you look in InputField.cs (which inherits from Selectable), the OnSelect() method does successfully get called when the input field is selected. I'm trying to replicate this within my own element without having to inherit from Selectable, and since Unity's event system is publicly accessible this should be possible.

Are there other requirements that will enable those events to fire and call my methods?


texts: Instantiating GameObjects in Custom Game Engine

texts:
So,i'm having a bit of an issue with instantiating my gameobjects into to universe(My Scene object).
I can create an empty object from scratch and populate it from there with ease,my problem starts when i try to clone the gameobject which i just created.
My steps are

I create an empty gameobject (GAMEOBJECT A)
I add an component to it (COMPONENT A)
Now i create a gameobject B from A
GameObject B created,and the component A is in the component list of the gameobject B
I try to get the component using inheritance but nullptr returns

It seems when i try to clone components,it returns only the base class pointer.There i try to recreate the derived class and add it to new gameobject's component list but obviously i fail.

If i cant solve this with inheritance how can i solve it ?
is there better way to implement such a desing ?
or i just fail to use inheritance in c++.If it's, can you guys point out what am i doing wrong here

This is my GameObject AKA RGameElement
class RGameElement
{
protected:
    vector<RElementComponent*> Elements;
public:
    template <class T>
    T* GetComponent() {

        int elementSize = Elements.size();

        for (int i = 0;i < elementSize;i++)
        {
            T* pr = dynamic_cast<T*>(Elements[i]);
            if (pr != nullptr)
                return pr;
        }
        return nullptr;
    }
    template <class T>
    T* AddComponent() {

        T* newElementComp = new T();
        Elements.push_back(newElementComp);
        return newElementComp;
    }
    void AddComponent(RElementComponent* targetComponent)
    {
        RElementComponent* newElement = new RElementComponent();

        *newElement = *targetElement;

        Elements.push_back(newElement);
    }

    /*void AddComponent(RElementComponent* targetComponent);*/
    vector<RElementComponent*> GetComponent() const;
}

This is my Component AKA RElementComponent
class RGameElement;

class RElementComponent
{
public:
    RGameElement* RootGameElement;
    virtual RElementComponent GetReference() { return RElementComponent(); };
    virtual void Setup() {};
    virtual void StartLogic() {};
    virtual void UpdateLogic() {};

}

and this my Instantiate via gameobject ref function
RGameElement* RUniverse::Instantiate(RGameElement* targetGameElement)
{
    RGameElement* newElement = new RGameElement();

    vector<RElementComponent*> components = targetGameElement->GetComponents();
    int componentSize = components.size();

    for (int i = 0;i < componentSize;i++)
    {
        newElement->AddComponent(components[i]);
    }

    Elements.push_back(newElement);
    return newElement;
}


texts: Simulate camera movement in two dimensions (OpenGL)

texts:
I've been told by the folks over at Stack Overflow that there's no way to move the camera in OpenGL. I'm developing a 2D RPG with LWJGL and need to know the proper way to simulate camera movement as though it is "following" my player. Remember, this game is in two dimensions, so rotation of the world is not a problem here.

And another, related question: If camera movement simulation involves moving the world and not the player, how would it be possible to ever implement multiplayer? I'm a bit of a noob at OpenGL, but I see it used in a handful of popular multiplayer Java games, and can't get my head around the concept of being unable to move the perspective (and thus being forced to move the world) and not having players interfere with each other's movement.


texts:
I'm new to game/graphics development and I'm playing around with particles (in 2D). I want to draw particles close to each other as a blob, just as liquid/water. I do not want to draw big circles overlapping as the blob won't be smooth (and too big). I don't really know physics but I assume what I want is something looking similar to surface tension.

I haven't been able to find anything on stackexchange or on Google (maybe I do not know the correct keywords?). So far I have found two possible solutions, but I am unable to find any concrete information about algorithms.

One of them is to calculate the concave hull of particles I consider being a blob. I can calculate the blob by creating an equivalence class (on the relation "close to each other"). Strangely enough I haven't been able to find any algorithm explaining how to calculate the concave hull. Many posts (and among stackexchange) links to libraries or commercial products that do this (I need libraries to work in C#), but never any algorithm. Also this solution might have a problem with a circle of particles, which would not detect the empty space in the middle.

While researching concave hull I stumbled upon something called alpha shapes. Which seems to be exactly what I want to do, however just as with concave hull I haven't found any source explaining how they actually work. I have found some presentation materials but not enough to go on. It's like a big secret everyone knows except me :-/

After calculating the concave hull or alpha shape I want to make it a Bézier curve to make it smooth and nice.

Although I do find my approach a bit too complex, maybe I am trying to solve this the wrong way? If you can either suggest any other solution to my problem, or explain the pieces I am missing I would be very happy and grateful :-)

Thanks.


texts: How can I enable flat surface reflections in UE4 on mobile?

texts:
Could someone please tell me how do I enable reflections on flat surfaces on a mobile in UE4? I have a simple room with one directional light. I need reflections on the tables and ground planes. I have tried every single setting and variation possible and nothing works.

I have tested the Sun Temple demo project and the Reflection Content Example demo project and nether of those projects have reflections on the mobile (iPhone 6). Those projects do have some kind of glare on the ground plans but noting close to what would be classified as a realistic reflection.

SSR does not work on mobile, neither do Sphere or Box Reflection captures. An alternative solution to get reflections working may be to use a Scene Capture Cube, but they don't work on mobile either.

UE4 is suppose to be an amazing game engine but it doesn't even offer the ability to support reflections on mobile. Reflections are quite simple to get running in Unity.

I have spent so much time trying to get reflections to work, and the worst thing is, every post or document that i have read about this subject does not offer a solution.

If someone could please confirm for me that reflections do not work on mobile or offer me a solution to get detailed reflections displaying on the ground and tables I would be so appreciative.


texts: Unity - An unwanted Collider , far too big , being added to meshes without reason and I cannot remove it

texts:
so I have a game in progress that is very similar to Asteroids. I was using spheres as primitive game objects and it all works perfectly in this case, but I need to be able to rotate the ship's model, and move the sphere as seperate entities and so I decided to keep the sphere for the positioning (but with no mesh renderer on it, just the sphere collider). And then as a child of that sphere is my model of a spaceship. It all works fine, ie. the ship rotation is completely seperate to that of the position of its parent sphere.

My problem is when I added the OnTriggerEnter to test collision between Ship to Asteroid. It would trigger immediately.

So I looked further into it, I zoomed right out on the Unity editor and could see that there is a huge collider that appears to be part of the mesh. (Now the mesh i did download from Blend Swap, but I have tried 3 varied ships and they have all done it - not to mention that I pulled them into Blender first and editted them so that it was just the ship part that I wanted and when I exported the OBJ/FBX's I ticked the box "Selected Only", - In a nutshell - I'm 110% sure there wasnt some little camera/light/object floating around that would cause the model to have such a big collider)

Secondly , I think I mentioned already, that in Inspector THERE ISNT ANY COLLIDER supposed to be attached to the mesh/model.

Heres a screenshot which I hope shows what I mean.

alt text

I really hope there is a way to fix/remove this as its been stopping me progressing any further and if it cant be removed I will have to start the whole game from scratch again.

Really I am also asking, why is there a collider even there when as you can see in the screenshot it clearly doesnt have any collider added. The parent has a collider, but this is the correct size and I can adjust/deactivate it as I'd expect. In my mind this collider pictured shouldnt exist.


texts: Limit a scrollbar's OnValueChanged to full step intervals only

texts:
So I have done some research on the matter but I can't find anything.

I created a UI scrollbar and asigned 10 steps to it.Then I noticed that the values of the scrollbar does not change in reference of the handle's steps but in reference of the pointer's position(like a slider).That seriously slows down the performance since it has a lot more to process "onValueChanged" and it is unnecessary for what I am trying to achieve.

The values of the steps should go step 1: 0.1(1),step 2: 0.2(2) etc.I need to get these values and nothing in between or the step that the handle is currently on.

How can I do that ?


texts: How to detect mouse over for UI image in Unity 5?

texts:
I have an image that I have setup to move around and zoom in and out from. The trouble is the zoom can be done from anywhere in the scene, but I only want it to zoom when the mouse is hovering over the image. I have tried to use OnMouseEnter, OnMouseOver, event triggers, all three of those without a collider, with a collider, with a trigger collider, and all of that on the image itself and on an empty game object. However none of those have worked...So I am absolutely stumped...Could someone help me out here!

Here is my script:

    private float zoom;
    public float zoomSpeed;
    public Image map;

    public float zoomMin;
    public float zoomMax;

    void Update () {
        zoom = (Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomSpeed);
        map.transform.localScale += new Vector3(map.transform.localScale.x * zoom, map.transform.localScale.y * zoom, 0);
        Vector3 scale = map.transform.localScale;
        scale = new Vector3(Mathf.Clamp(map.transform.localScale.x, zoomMin, zoomMax), Mathf.Clamp(map.transform.localScale.y, zoomMin, zoomMax), 0);
        map.transform.localScale = scale;
    }


texts: Why Do Textures Appear Black In OpenGL 4.5 In Windows?

texts:
I usually code in Linux, and when I ran my OpenGL program the textures displayed correctly. However, when I ran it on Windows the textures appeared black until I used old OpenGL for the textures. Is there anything wrong in the code that creates the texture?

        int[] pixels = null;
    try {
        BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/" + path));
        width = image.getWidth();
        height = image.getHeight();
        pixels = new int[width * height];
        image.getRGB(0, 0, width, height, pixels, 0, width);
    } catch (IOException e) {
        e.printStackTrace();
    }

    int[] data = new int[width * height];
    for (int i = 0; i < width * height; i++) {
        int a = (pixels[i] & 0xff000000) >> 24;
        int r = (pixels[i] & 0xff0000) >> 16;
        int g = (pixels[i] & 0xff00) >> 8;
        int b = (pixels[i] & 0xff);

        data[i] = a << 24 | b << 16 | g << 8 | r;
    }

    textureID = GL45.glCreateTextures(GL11.GL_TEXTURE_2D);
    GL45.glBindTextureUnit(0, textureID);
    GL45.glTextureStorage2D(textureID, 1, GL11.GL_RGBA, width, height);
    GL45.glTextureParameteri(textureID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    GL45.glTextureParameteri(textureID, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    GL45.glTextureSubImage2D(textureID, 0, width, 0, 0, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data);
    GL45.glBindTextureUnit(0, 0);

EDIT: The answer was very simple. I had forgotten to do GL11.GL_RGBA8 instead of just GL11.GL_RGBA when doing GL45.glTextureStorage2D. This threw a GL_INVALID_ENUM error which caused glTextureSubImage to not store anything, causing the texture to be black. It was strange that this problem did not occur on Linux, though.

I will leave this problem open, as some commenters have pointed out that there is something majorly wrong with how I use the new DSA features.


texts: How is a normal map applied to a triangle mesh?

texts:
I'm working on writing my own parser/renderer for the obj file type, and right now I have it working so that I can draw the model correctly and use the vt texture coordinates to apply a texture to the model. The next step that I want to do is apply a normal map to make the surface look smoother, but I'm not completely sure how this is done.
I've applied normal maps to a sphere before, and part of the trouble that I had in implementing that was figuring out how to get a consistent pair of tangent vectors in order to adjust the normal. On a sphere, that's done using spherical coordinates and calculating dp/du and dp/dv, but how is it done in an obj file? It seems like local coordinates, normal coordinates, and texture coordinates are the only thing stored for each vertex, no tangent vectors. I know that the surface can also be smoothed by interpolating the normal vectors defined at each vertex, but the model I'm working with doesn't even have those defined. And I know it should be possible with the model because if I open it in the windows 3d viewer I can see that it smooths out the triangles.
How are the tangent vectors found on a triangle mesh? In case it matters, the specific model that I'm using is one that I downloaded from here.


texts: How do I implement a selectable world map?

texts:
I want to have a selectable map of the world, preferably zoomable, in a cocos2d project. When I tap on a country, I want that country to be selected so that I can perform some other operations with it. It seems that the best approach would be to use a vector world map, but I'm unsure how to implement this with cocos2d. Other options include using map tiles, but it seems that still would require the implementation of country polygons for tap/click detection.

Depending on user input, I want to add icons to various countries on the map.

What is a good way to approach the implementation of this type of map?


texts:
I really don't understand why this is creating these kinds of artifacts. I'm starting to think something is wrong with Unity.

There are clearly no overlapping faces on the Model. There is enough of a margin to remove all chances of bleed. Yes the lid is a seperate object but any UV's of the lid and it's box are not overlapping. Thix odd pixelation occurs no matter the quality. It happened all the time sofar here and there and it forced me to replace a few objects in older projects. No idea what causes it. Really sick and tired of this.

Edit:

when I rotate the crate by 90 degrees the artifacts appear on the adjacent side of the cube. From the perspective of the camera it would be the same side. So clearly it's not the UV's or anything.

Lightmap settings

Object Import settings


texts:
I'm using Moai SDK. I have an image and some random convex 2D polygons. I want to show only the parts of the image inside these polygons.

Here's an example image:

The same, shown only where the polygons are:

How can I achieve this?


texts: What is the difference between PBR and SSR?

texts:
I am very new to game development and I have been trying to understand the difference between Screen Space Reflection and Physically Based Rendering.

I have read about PBR, and from what I understand, it tries to mimic how light reflects in real life, which is it usually gets split to two components, specular and diffuse depending on the type of material.

As for SSR, pls correct me if i am wrong, it is how reflections look on a surface.

If my understanding of SSR is correct, then aren't they in a way the same? I mean, isn't the way reflections look on a surface dependent on the surface roughness and etc. This will then affect how much light is specularly reflected and how much is diffusely reflected. Again, please correct me anywhere I am wrong.


texts: So I need to clip polygons against polygons where one of it is behind the other. But just drawing it is for my desired hardware just too slow. My polygons only have four lines so what can I do?


texts: Why do I get these weird errors when using pow() for my game?

texts:
/usr/bin/ld: /tmp/ccfm5eKc.o: undefined reference to symbol 'pow@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

I get this error when trying to use pow(). Why?


texts: What are some ways to implement variable body shapes?

texts:
Games like Ryzom and the Sims allow players to have human bodies with different shapes: wide or thin, tall or short, big noses or small, etc.  It seems to me that it'd be impractical to pre-generate all possible combinations of the meshes.

What are some ways to do that?  Are the meshes defined programmatically? Is it a weighted average of multiple "morph target" models?

If there is calculation to be done to determine the mesh: is it done in a "geometry shader"?  Or is it done by the CPU?

Reference: The question "How to create art assets for 3d avatar editor" mentioned avatar editors and variable body elements, and that some games use morph targets and glyph bombing.


texts:
I recently downloaded the JBox2D but how do I set this up?

It's jbox2d-2.1.2.2. All I can see is a bunch of code and folders.


texts: Setting up collision using a tilemap and cocos2d

texts:
I'm building my first platformer using cocos2d and a tilemap. I'm having trouble coming up with a decent way of determining if the character is colliding with an object. More specifically, in which direction is the character colliding with an object.

Following the tutorial here, I have made a separate "meta" layer of collidable tiles. The problem is that unless the character is in the tile, you can't detect the collision. Also, there's no way of telling WHERE the collision is occurring.

The best solution would be one that could tell me if a character is up against a wall, or walking on top of a platform. However, I can't seem to figure out a good technique for this.


texts: WoW lua: Getting quest attributes before the QUEST_DETAIL event

texts:
I'd like to determine the attributes of a quest (i.e.,  information provided by functions such as QuestIsDaily and IsQuestCompletable) before the player clicks on the quest detail.

I'm trying to write an add-on that handles accepting and completing of daily quests with a single click on the NPC, but I'm running into a problem whereby I can't find out anything about a given quest unless the quest text is currently being displayed, defeating the purpose of the add-on. Other add-ons of this nature seem to be getting around this limitation by hard-coding information about quests, an approach I don't much like as it requires constant maintenance.

It seems to me that this information must be available somehow, as the game itself can properly figure out which icon to display over the head of the NPC without player interaction. The only question is, are add-on authors allowed access to this information? If so, how?

EDIT: What I originally left out was that the situations I'm trying to address are when:

An NPC has multiple quests
The quest detail is not the first thing that shows up upon right-click

Otherwise, the situation is much simpler, as I have the information I need provided immediately.


texts: Why is it that I’m still able to call a coroutine from another script, even though I marked it as private?

texts:
I have this private coroutine in my WinDialogue script:

private IEnumerator ActivateStars(int count)
{
    for (int i = 0; i < count; i++)
    {
        _stars[i].SetActive(true);
        yield return new WaitForSeconds(.3f);
    }
}

And somehow I’m still able to call it from my UIManager script:

_winDialogue.GetComponent<WinDialogue>().StartCoroutine("ActivateStars", starCount);

How can that be if I marked it as private?


texts:
I have a scene that consists of 1 player object, 1 platform, 1 enemy, and 1 background. Currently, this is how my render function looks like:

void Sprite::Render()
{
    glUseProgram(m_Program);
    glActiveTexture(GL_TEXTURE0);

    // Background
    glBindVertexArray(BackgroundVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[1]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture1"), 0);

    m_ProjectionMatrix = m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    // Enemy
    glBindVertexArray(EnemyVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[2]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture3"), 0);

    m_ProjectionMatrix = glm::translate(glm::mat4(), glm::vec3(EnemyX, EnemyY, 0.0f)) * m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    // Platform One
    glBindVertexArray(PlatformVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[3]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture4"), 0);

    m_ProjectionMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, -0.5f, 0.0f)) * m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    // Player
    glBindVertexArray(PlayerVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[0]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture2"), 0);

    m_ProjectionMatrix = glm::translate(glm::mat4(), glm::vec3(PlayerX, PlayerY, 0.0f)) * m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    glBindTexture(GL_TEXTURE_2D, 0);
    glBindVertexArray(0);
}

As you can see, it is unnecessarily complicated. And if I want to draw, say, two or more enemies, or 4 or more platforms, then it'd get ridiculously large! My question is this, how can I make this smaller? I prefer to be able to do something like this in my main.cpp: Sprite.Render(Player); Sprite.Render(EnemyOne); etc...

Looking forward to reading your tips, thank you!


texts: How can I compress resources into a single file in Java?

texts:
Today I've finished my game, but there's a problem. There're more than 500+ images in my resources folder and I want to compress them into a single file, like other games do (for example put everything in a .pak file). I've searched on the internet, but I can't find something that tells about how to do it with Java.

There's maybe a library that I can use to avoid that problem?

Thanks.


texts: Why would one have "waves" in each stage of a tower defense game?

texts:
For example, in Plants vs Zombies, the zombies come in waves.  If I recall, there's always at least two waves. The first and easier wave and then when you get 90% through the stage there's a "final wave" which is shorter, harder, and has a bunch of zombies all come at once.

My question is, why would a game decide to announce when you change from one wave to the next?  They could have just let the level progress from start to finish without this if they wanted to.

Does this make the game more fun for some reason?  Where can I learn more about this technique (eg: does it have a name)?


texts: Switching from one solution to another in visual sudio

texts:
I have been able to bring a number of projects together like this:

But now, whenever I try to switch from "Bitmap Loading and Drawing" sln(do realize bold letters) to another sln, I am unable to do so.

I even tried to click on another sln's file. It does come out but if I try to build the latter sln file... the former sln gets built.

what is the correct way to switch from one solution to another?

Thanks in advance.


texts: Why the main menu is not working on the second time when pressing on escape key to back to the main menu?

texts:
I have two scenes. Main Menu and the main scene.
The game start when only the main menu is loading.

When I click on the New Game button it's loading the main scene and removing the main menu scene.

If I click now on the Escape key it will remove the main scene and load back the main menu scene but this time I can't click on any of the buttons in the main menu.

I'm not sure if this is the right way to switch between the scenes but it's not working good.

On the Newgame button I created and attached a new script. And then in the OnClick event of the button I'm calling the method LoadByIndex:

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

public class LoadSceneOnClick : MonoBehaviour
{
    public void LoadByIndex(int sceneIndex)
    {
        SceneManager.LoadScene(sceneIndex);
    }
}

On the main scene I added a empty gameobject and attached to it another script:

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

public class BackToMainMenu : MonoBehaviour
{
    public int sceneIndex;

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene(sceneIndex);
        }
    }
}

When the game start in the main menu when clicking on New Game button it's loading index 1 the main scene and removing the main menu.

When clicking on escape key it's loading index 0 and removing the main scene.
But then the main menu is not working.


texts: If you create a game, do you automatically have the rights to it?

texts: I am creating a game in c++ that will me multiplier and am going to post it on https://indiegamestand.com  Here is one of the requirements "Must own the rights to distribute your game and to assign those rights to us (non-exclusively) for the purpose of selling here."  If I compile my game as an .exe do I have that right?  How can I make sure I retain it, and what can they do with the game if I give them that right?


texts:
I want to apply textures to a 3D Model in XNA 4.

Whatever I saw on the internet was to apply the textures in the modeling tool and then load the model (*.fbx) into XNA.
Is it possible to load the Model into XNA game first and then apply the Texture into its Meshes somehow?


texts: OnTriggerEnter doesn't detect collision until at least one of the two colliders move

texts:
I'm having trouble coding a melee attack script.

I've set up an attack hitbox that toggles enabled/disabled whenever you press a button (The hitbox itself doesn't move, it just blinks in and out) and I'm trying to have it hit an unmoving target. The first hit gets registered, but the next do not unless I move either the static target (by pushing it) or the player itself.

Both the hitbox and the hurtbox have kinematic rigidbodies in them. They are separate BoxCollider2Ds in their own "Hitbox" and "Hurtbox" layers, which only interact between themselves. My hit detection code is as follows:

void OnTriggerEnter2D(Collider2D col) {
    Debug.Log(col + " got hurt");
}

Here's a graphical example of what's going on. You can see how hit detection doesn't work until I nudge Test Monster. When I try to attack it without moving it, detection stops working.


texts: Why are god objects so common in game programming?

texts:
This is a bit of a philosophical question. Excuse me if it's out of place here.

Most modern games developed in C++ use (or at least purport to use) an object-oriented approach. A common axiom of object-oriented design is that a class should have a single, self-evident responsibility. I think that's good advice: You should be able to look at a class definition, take in the list of member functions, and know what a class is designed to do. If your public interface has 50+ functions, you're probably doing something wrong.

Here is the list of public member functions declared in the player character class for Unreal's sample shooter game.

class AShooterCharacter : public ACharacter
{
    virtual void PostInitializeComponents() override;
    virtual void Tick(float DeltaSeconds) override;
    virtual void Destroyed() override;
    virtual void PawnClientRestart() override;
    virtual void PossessedBy(class AController* C) override;
    virtual void OnRep_PlayerState() override;
    void OnCameraUpdate(const FVector& CameraLocation, const FRotator& CameraRotation);
    FRotator GetAimOffsets() const;
    bool IsEnemyFor(AController* TestPC) const;
    void AddWeapon(class AShooterWeapon* Weapon);
    void RemoveWeapon(class AShooterWeapon* Weapon);
    class AShooterWeapon* FindWeapon(TSubclassOf<class AShooterWeapon> WeaponClass);
    void EquipWeapon(class AShooterWeapon* Weapon);
    void StartWeaponFire();
    void StopWeaponFire();
    bool CanFire() const;
    bool CanReload() const;
    void SetTargeting(bool bNewTargeting);
    void SetRunning(bool bNewRunning, bool bToggle);
    virtual float PlayAnimMontage(class UAnimMontage* AnimMontage, float InPlayRate = 1.f, FName StartSectionName = NAME_None) override;
    virtual void StopAnimMontage(class UAnimMontage* AnimMontage) override;
    void StopAllAnimMontages();
    virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override;
    void MoveForward(float Val);
    void MoveRight(float Val);
    void MoveUp(float Val);
    void TurnAtRate(float Val);
    void LookUpAtRate(float Val);
    void OnStartFire();
    void OnStopFire();
    void OnStartTargeting();
    void OnStopTargeting();
    void OnNextWeapon();
    void OnPrevWeapon();
    void OnReload();
    void OnStartJump();
    void OnStopJump();
    void OnStartRunning();
    void OnStartRunningToggle();
    void OnStopRunning();
    USkeletalMeshComponent* GetPawnMesh() const;
    class AShooterWeapon* GetWeapon() const;
    FName GetWeaponAttachPoint() const;
    int32 GetInventoryCount() const;
    class AShooterWeapon* GetInventoryWeapon(int32 index) const;
    float GetTargetingSpeedModifier() const;
    bool IsTargeting() const;
    bool IsFiring() const;
    float GetRunningSpeedModifier() const;
    bool IsRunning() const;
    virtual bool IsFirstPerson() const;
    int32 GetMaxHealth() const;
    bool IsAlive() const;
    float GetLowHealthPercentage() const;
    USkeletalMeshComponent* GetSpecifcPawnMesh(bool WantFirstPerson) const;
    void UpdateTeamColorsAllMIDs();
    virtual float TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, class AActor* DamageCauser) override;
    virtual void Suicide();
    virtual void KilledBy(class APawn* EventInstigator);
    virtual bool CanDie(float KillingDamage, FDamageEvent const& DamageEvent, AController* Killer, AActor* DamageCauser) const;
    virtual bool Die(float KillingDamage, struct FDamageEvent const& DamageEvent, class AController* Killer, class AActor* DamageCauser);
    virtual void FellOutOfWorld(const class UDamageType& dmgType) override;
    virtual void PreReplication( IRepChangedPropertyTracker & ChangedPropertyTracker ) override;
};

Why is this acceptable? Isn't there a better way?


texts: Light point buggy on old device after migrating to URP

texts:
Light point is very buggy on Samsung A5 after migrating to URP, it works well on PC and Samsung A7.
Altought it has light points, these are really few and using lowest settings by default, all other graphic stuff is lightweight and runs well.
Does someone know if it's expected or what can I do? I tried to reduce the lightning settings and add OpenGL-ES 2, but I've got the same results.


texts: How to generate a rotation matrix or a quaternion (properly rotated in regards to texture coordinates) for each triangle of a mesh?

texts:
I'm trying to build a uniform grid made of 3D points over the surface of an arbitrary mesh (we have texture-coordinates for each vertex...)

Or to reformulate: imagine a mesh textured with a texture featuring equally spaced dots: I want to obtain the 3D coordinates of these dots.

So far, I'm able to generate a normal for each triangle of the mesh but it is not enough.

If I had the right matrix, or quaternion or even orthonormal-basis for each triangle, I guess that I could transform any 2D coordinates (on the triangle's plane) to 3D coordinates (in object space...)

The problem is how to rotate properly in regards to texture coordinates?

To be more specific: for each triangle, I can define a normal. It could serve as the x,y,z part of a quaternion. But how could I generate the w part?


texts: Help on transition from one position to another

texts:
I'm pretty sure I'm over thinking stuff, but I can't seem to figure this out. I want to move the object from one location to another. Here's what I got. I searched this up earlier here, and I found something similar, but I wasn't able to make it work. Any help would be appreciated, thanks.

//the current position of the object is at 400, 300
Vector2 nextPosition = new Vector(100, 200);
Vector2 difference = nextPosition - position;

difference.Normalize();

position += difference * 5;


texts: Passing data into a vertex shader for perspective divide

texts:
In OpenGL and GLSL, I am just learning about perspective projection and the vertex shader. However, I am a little confused about what data actually needs to be passed to the vertex shader, and what needs to be done in the shader code itself.

I have two questions:

Suppose I have a triangle defined in 3D coordinates (x,y,z). Do I need to pass a 4D vector with values (x,y,z,w), where w = z? Or do I just pass the 3D vector? The reason I ask is that I know that somewhere in the pipeline, the x and y coordinates are divided by the w component, in the perspective divide.

In the vertex shader code, do I need to manually divide the x and y components by the w component myself? Or is this taken care of automatically?

Thanks!


texts: What's the best presentation/terminology for "quit" functionality?

texts:
I'm writing a game in XNA for Windows and Xbox, and I'm trying to decide how to present quitting options to the user. It seems to me that there are two basic types of "quits":

Quit the game and close it completely. On the PC, return to Windows. On the Xbox, return to the Dashboard.
Quit the current playthrough and return to the title screen.

Is there accepted language for these things? I've tried a few basic searches - I apologize if this has already been asked - but I couldn't find anything. The best I can come up with is this:

Provide a "Quit" option on the title screen menu. This will close the game completely (see #1 above). This might not be strictly necessary on the Xbox, since players can close games using the Guide button (aka the "Xbox button").
Provide an "Exit to Title Screen" option elsewhere in the game. This will quit the current game and return to the title screen (see #2 above).

I don't love the latter option, because it's a bit too verbose for my tastes, but using something shorter, e.g., just "Quit" and "Exit", doesn't seem clear enough.

It seems like the word "Quit" is the logical choice in both places, but wouldn't using the same word for two different things be inconsistent and confusing?

What are other "quit" conventions that you've seen?


texts: How can I use collision lines to implement line-of-sight in GameMaker?

texts:
I am making a GameMaker game that involves the enemies having line of sight so that they don't target the player through a wall. I have this code that uses collision line to detect whether there is a wall between the enemy and the player, then sets CanSee to 1 if true.

if collision_line(x, y, obj_parent.x, obj_parent.y, obj_wall_parent, false, true)
    global.CanSee = 1;

However, this code does not ever affect the value of CanSee. Am I using this code wrong?

Edit:
Here is my room setup. The walls all have obj_wall_parentas their parent.

Here are some of the objects:


texts: Do game studios hire people based on their math knowledge alone?

texts:
I have very little programming skills outside of very basic levels of Java, but I have excellent math and science knowledge. I was wondering what I could offer any potential team if I were to go into video game development? Do people hire people based on their math knowledge alone?

I like to do other things such as writing or drawing, but math and science are the only skills in which I really excel in.


texts: How to resolve collisions of compound shapes using SAT?

texts:
SAT is a decent way to determine collisions between arbitrary convex polygons. You'll even get the vector that is needed to resolve a collision.

To resolve collisions between complex (non-convex) shapes, I was thinking about some sort of compound-shape which consists of several convex polygons. If a collision occurs in the broad-phase (eg. circle vs. circle or AABB vs AABB), the collision would be resolved by checking each polygon in the compound shape vs. each polygon in the other compound shape.

I wonder what's the best way to actually separate the objects though? A naive approach would be to just take the vector with the highest magnitude and use that for separation. In the following picture, this would be V2

However if the separating vectors point into different directions, the collision cannot be resolved right away and might require several iterations. So in the next picture we would separate using V1 and in another iteration by V2 (or something close to V2, as the shape would have moved by the amount of V1).

This approach will fail with separating vectors that point into the opposite direction of each other or in a case like shown in the following picture:

Here we would iterate endlessly between the state on the left and the state on the right.

So to ask an actual question here: What's a reasonable approach to this problem? I guess using compound polygons for complex shapes is a reasonable idea but I really wonder how collisions should be resolved in that case? How do I detect a dead-end as shown in the third image?


texts:
I need to download a file (a .ogv video) from a server using a UnityWebRequest.

Let's say the file is located at home/folder1/folder2/file.ogv on the server, and the IP adress of the server is 1.2.3.4. I tried to create my web request with:

webRequest = UnityWebRequest.Get("1.2.3.4/home/folder1/folder2/file.ogv");

However when this web request is sent, nothing happens.

webRequest = UnityWebRequest.Get("1.2.3.4/home/folder1/folder2/file.ogv");
DownloadHandler receiveBundle = new DownloadHandlerBuffer();
webRequest.downloadHandler = receiveBundle;
webRequest.Send();


texts: Is it bad practice to set the velocity of an object every loop?

texts: Say I have a simple game with a gameLoop function that gets called every 50 milliseconds or something similar, and I have a box2d object. Is it bad practice/too CPU intensive to use SetLinearVelocity on the object every time the gameLoop is called?


texts:
I'm using a quadtree to prune collision detection pairs in a 2d world. How should I choose to what depth said quadtree is calculated?

The world is made mostly of moving objects1, so the cost of dispatching the objects between the quadtree cells matters. What is the relationship between the gain from less collision checking and the loss from more dispatching? How can I strike a balance that performs optimally?

1 To be completely explicit, they are autonomous self-replicating cells competing for food sources. This is an attempt to show my pupils predator-prey dynamics and genetic evolution at work.


texts: RTS Balancing for Units with Different Costs

texts:
I am creating a space-based RTS. So far, we have three units:

Fighters (cost 5 resources)

Interceptors (cost 20)

Rocket Ships (cost 40).

I've designed this game in a Rock-Paper-Scissors format (Fighters beat Interceptors, Interceptors beat Rocket Ships, Rocket Ships beat Fighters), but the game is designed so that classes beat each other at cost (i.e. a single Interceptor will beat a single Fighter, but four Fighters (cost 20) will beat a single Interceptor (cost 20)).

In this case, when I am using the Incomplete Wins technique to calculate the proportions of each ship that I would expect to see, should I calculate interactions using 1v1 interactions or "at cost" interactions? I believe the two will lead to very different results (for example, a single Fighter does 20% of damage to Interceptor before it itself is destroyed, but four Fighters destroy the Interceptor while only losing one ship; the first interaction leads to a 1 resource advantage for the Interceptor player, while the second interaction leads to a 15 resource advantage for the Fighter player). I would think it I should do the latter comparison, but the linked page does a single unit comparison (one Knight vs one Archer, even though Knight costs half that of Archer)

EDIT: This RTS is partially derived from Total Annihilation/Supreme Commander, so no projectiles hit instantly and the scale of the game is intended to be somewhat large. In that case, should I instead perform comparisons between armies that cost the same? For example, instead of comparing one Fighter vs one Interceptor or four Fighters vs one Interceptor, should I instead compare 40 Fighters vs 10 Interceptors? Would that be more accurate and also help reduce randomness of projectile hits?


texts: How do I double-buffer renders to a JPanel?

texts:
I'm trying to make a little breakout game with Java and Swing. The only issue so far is that drawing on the JPanel causes lots of flickering!

The relevant code:

JFrame frame = new JFrame("Breakout");
JPanel gameField = (JPanel) frame.getContentPane();

private void gameLoop() {
    while(running) {
        update();
        render((Graphics2D) gameField.getGraphics());
    }
}

private void render(Graphics2D g) {
    g.clearRect(0, 0, gameField.getWidth(), gameField.getHeight());
    for (GameObject o : objects) {
        o.draw(g);
    }
}

I've looked into manually double buffering (e.g. by making an offscreen Image, drawing on it, then doing g.drawImage(offscreen). Is there a better way?


texts: Are shaders the only way to implement 2d lighting?

texts:
I'm working on a 2d top down game with libgdx and I think i got the basics. No want I want to implement lighting, I don't know anything about lighting. I want just to have some light sources and shadows, but how do i do it?

Is using glsgl the only wayto do lighting in a 2d game? I've already tried to learn opengl and gave up because i thought it was too dificult and could take too long to do something even if i got the basics. Mabye glsl is different anyways

Any examples/tutorials would be welcome.
Thanks in advance


texts: How do I allow a player to manager several games at once with different players using game center?

texts: I wish to do a turn based multiplayer game like Words with friends on the iphone. I would like to know the approach for the implementation to allow the user to continue games that are currently still active even after a couple of days. Is this even possible using Game Center?


texts: How can I "publish" an Android game without Google Play?

texts:
I'm new to development and trying to get a sense for the obstacles to publication

If I need to circumvent the Google Play app store, can I publish a game to a website that people can visit in a mobile browser and download and install like any other app?

How does publishing "around" Google Play work? Are there any particular success stories, best practices or problems I should be aware of?

Apologies if there is an obvious answer. I believe I found the answer at one point, but I don't remember and can't find the link.

edit: Thanks everyone! I really appreciate the help. Definitely answers my questions. Looks like I have some options!


texts: How to raycast against a physx cloth mesh?

texts:
I'm using the PhysX 3.3 SDK in a application and mostly everything is working fine. However, I'm trying to develop a feature that would allow users to click on various actors in the scene and modify their properties.

My approach so far has been to use the PhysX raycast to query the scene and use RaycastHit to return a pointer to the actor. This works fine for rigid bodies, but for cloth actors, the hit is invariably null.

This suggests that PhysX can't raycast against cloth objects, but other than my tests, I haven't seen anything in the docs (or on the interwebs) that say this definitively.

Any thoughts?


texts: Camera animation stutters on first launch

texts:
The camera stutter for a fraction of a second when animating a camera from one position to another position. This issue only happens when the game is launched for the first time after installation. The camera animation is smooth for further game launches.
I am using LeanTween to animate the camera. No data is loaded while the camera is animating.
Environment:
Unity version: 2019.3.03f
Mobile platform: iOS
iOS versions: 12 and above
More information:
The assets are being initialized and loaded on the first screen. I have a module to initialize all the assets before the camera starts panning. I also seeing stutters on the first installation for certain 3D objects animation; these objects are also loaded on the first screen. I don’t know what else to improve with the initialization.
Since we can’t run Unity’s profiler on real devices, I ran the profiler on Unity’s editor and looked at the call stacks at the points where you see the spikes. Below is the screenshot of the call stack of a spike during a specific animation stutter:

I made the following changes:

Instead of LeanTween, I used my own code for camera animation
Disabled all UI animations
Disabled analytics solutions
Disabled the camera’s occlusion culling property
Camera animation using Unity Timeline

However, these changes did not affect the stutters.
Also, I am not seeing the stutters in the editor but they are clearly visible on a device. I can’t profile the game on a device using Xcode since it is not using native code.
I ran the same code on a few Android devices and I am not seeing the stutters there.
I would appreciate any suggestions and thoughts on this topic. Thank you.
Code structure:
My game has three screens (A, B, and C). All the mesh files, materials, and game objects present on screens B and C are initialized and set to be active from the start of the game; in other words, everything is loaded on screen A before the animation to screen B begins. Occlusion culling is on for the camera.
The camera stays on screen A for 3 seconds and then animates to screen B. After the user performs a certain action on screen B, the camera animates to screen C.
The stutters happen when the camera is halfway between screens A to B and halfway between screens B to C.


texts: How do I apply domain warping to my marching cubes voxel terrain in Unity?

texts:
So, in GPU Gems 3 there is a cool warped terrain that I seek to replicate.
Currently, I'm generating the terrain fine, but I want to add that warp effect.

// Do this before using 'ws' to sample the nine octaves!
float3 warp = noiseVol2.Sample( TrilinearRepeat, ws*0.004 ).xyz;
ws += warp * 8;

Im wondering how to replicate the above code in C#. What does the above code do? What type of variable is noiseVol2.Sample(x,y).xyz?

I want to warp my own terrain, currently I have a system that creates octaves of perlin noise with certain frequencies and amplitudes.

It looks something like this:

var perlin0 = new Perlin3(0,baseFreq  * 4.03f, 0.25f);
var perlin1 = new Perlin3(1, baseFreq * 1.96f, 0.50f);
var perlin2 = new Perlin3(2, baseFreq * 1.01f, 1.00f);
var perlin3 = new Perlin3(3, baseFreq * 0.49f, 2.00f);
var perlin4 = new Perlin3(4, baseFreq * 0.24f, 4.00f);

return new Density(ws => {

        // start with plane
        float density = plane.Evaluate(ws);

        // add perlin noise to get density values at each ws co-ord.
        //3 octaves currently (3 perlin noise +=)
        density += perlin0.Evaluate(ws);
        density += perlin1.Evaluate(ws);
        density += perlin2.Evaluate(ws);
        density += perlin3.Evaluate(ws);
        density += perlin4.Evaluate(ws);
        return density;
    });

I've tried replicating it like so:

var q = new Vector3(perlin0.Evaluate(new Vector3(0,0,0)), perlin0.Evaluate(new Vector3(5.2f, 1.3f, 1.3f)));
var q1 = new Vector3(perlin1.Evaluate(new Vector3(0, 0, 0)), perlin1.Evaluate(new Vector3(5.2f, 1.3f, 1.3f)));
var q2 = new Vector3(perlin2.Evaluate(new Vector3(0, 0, 0)), perlin2.Evaluate(new Vector3(5.2f, 1.3f, 1.3f)));
density += perlin0.Evaluate(p + 4.0f*q);
density += perlin1.Evaluate(p + 4.0f * q1);
density += perlin2.Evaluate(p + 4.0f * q2);

I've read the article that Íñigo Quílez created, and implemented it like above. Am I doing something wrong? It looks the same without that, just using

density += perlin0.Evaluate(p);
density += perlin1.Evaluate(p);
density += perlin2.Evaluate(p);

I want to know what I'm doing wrong, what I misunderstood and how to implement it correctly.

This is all based off this lumpn's proceedural-generation on github
(I would link it, but I can't)

Thanks.

I would also want to know if there are any examples (I learn best from codebases) with this implementation using shaders. (Maybe it will run faster because it uses the GPU instead of the CPU?)

This is still unanswered on how to do it on the CPU
(and I'm still confused on how to do it on the GPU, do you have to do some vertex stuff? how do you pass in a noise texture through the shader?)


texts: Rotate camera around offset to player position (third person shooter view)

texts:
I'm trying to rotate my camera 'next to' the player object so that the player is not in the way of the screen-centered reticle. What I am trying to achieve is something like the targetting system of Fortnite, GTA 5 or Red Dead Redemption (or most third-person shooters), where the camera/player are offset slightly so that you can see directly in front of them.
My code so far allows me to rotate the camera about the player (object here) and it follows the player's position. I cannot figure out how to offset it.
public void update(final GameObject object)
    {
        this.newMouseX = Input.getMouseX();
        this.newMouseY = Input.getMouseY();

        final float dx = (float) (this.newMouseX - this.oldMouseX);
        final float dy = (float) (this.newMouseY - this.oldMouseY);

        // Rotate the camera on mouse move
        this.verticalAngle -= dy * this.mouseSensitivity;
        this.horizontalAngle += dx * this.mouseSensitivity;

        // Distances from side view
        final float horizontalDistance = (float) (this.distance * Math.cos(Math.toRadians(this.verticalAngle)));
        final float verticalDistance = (float) (this.distance * Math.sin(Math.toRadians(this.verticalAngle)));

        // Distances from top view
        final float xOffset = (float) (horizontalDistance * Math.sin(Math.toRadians(-this.horizontalAngle)));
        final float zOffset = (float) (horizontalDistance * Math.cos(Math.toRadians(-this.horizontalAngle)));

        this.position.set(object.getPosition().getX() + xOffset, object.getPosition().getY() - verticalDistance + VERT_OFFSET, object.getPosition().getZ() + zOffset);

        this.rotation.set(-this.verticalAngle, this.horizontalAngle, 0);

        this.oldMouseX = this.newMouseX;
        this.oldMouseY = this.newMouseY;
    }

This is the sort of thing I'm trying to achieve:


texts:
I'm writing a shader that animates "pinching" an image and releasing it. It's similar to this shader on shadertoy.

One issue I have is that my shader should only "animate" once - meaning the image should appear to "pinch", then "unpinch", but then stop. Like this example, it'll keep going since the animation ia time-driven.

Since the shader is called for each pixel I don't see any easy way to track how many "animation iterations" there have been for the entire image.

I can handle animation via a Unity Update method, where I can easily control when to stop, but I'd rather do this entirely in-shader if at all possible.

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord.xy / iResolution.xy;

    vec2 center = vec2( .5 );
    vec2 dir = normalize( center - uv );
    float d = length( center - uv );
    float factor = .5 * sin( iTime );
    float f = exp( factor * ( d - .5 ) ) - 1.;
    if( d > .5 ) f = 0.;

    fragColor = texture( iChannel0, uv + f * dir );
}


texts: How to blend biomes with procedural terrain

texts:
I'm working on a terrain generator. Through multiple noise functions, I'm able to create many kinds of terrain I like, but I'm having a bit of difficulty joining them together in a seamless fashion.

My first thought was to use a single noise call (calling it the mask) and then I could simply say things like:

if (returnVal < .1) GenerateBiome1();
if (returnVal < .2) GenerateBiome2();
if (returnVal < .3) GenerateBiome3();

and so on...

The issue here is that the height of the terrain doesn't blend together when doing this. If biome 1 was more mountainous and biome 2 was flat land, it's a drastic switch from one to the other and it looks atrocious.

My next thought was to attempt blending by giving a 'strength' to each biome based on what my mask noise returns. In C# code, it looks something like this at the moment:

static public float GetHeight(float X, float Z)
{
    float fRollingHills_Location = .25f, fRollingHills_Impact = .5f, fRollingHills = 0;
    float fMountains_Location = .75f, fMountains_Impact = .5f, fMountains = 0;

    float fMask = Game1.GetNoise2(0, X, Z, .01f);
    float fRollingHills_Strength = (fRollingHills_Impact - Math.Abs(fMask - fRollingHills_Location)) / fRollingHills_Impact;
    float fMountains_Strength = (fMountains_Impact - Math.Abs(fMask - fMountains_Location)) / fMountains_Impact;

    if (fRollingHills_Strength > 0) fRollingHills = fRollingHills_Strength * (Game1.GetNoise2(0, X, Z, .02f) * 10f + 10f);
    if (fMountains_Strength > 0) fMountains = fMountains_Strength * (Game1.GetNoise2(0, X, Z, .05f) * 25f + 10f);

    return fRollingHills + fMountains;
}

The issue I have here is that even for only two biomes, it's pretty important for me to manually choose the "location" and "impact" values to ensure I'm getting some combination of strengths to total 100% by the time it returns a value (if not, I get things like giant cliffs making the borders from one biome to another ugly and obvious).

I don't know if I can give a good true question here other than, how should I actually be going about this? While I've managed a few good looking maps, I feel like I'm going about this in an overly complicated way that still doesn't give me all the customization I'm looking for.


texts: Are there any comprehensive resources for learning Google's PlayN framework?

texts:
How do I learn to use the PlayN framework?

The Getting Started page is not enough. I have been searching for some resources to learn PlayN but am unable to find any.

(P.S.: Does PlayN require GWT?)


texts: Colouring greyscale images/sprites for HTML canvas

texts:
What is the best method to colour in sprites at runtime using the canvas element and javascript? I know there are various blending modes using globalCompositeOperation, but I don't know how best to utilise this.

I'll break my question down into the following:

Is there an optimum way to export greyscale images so they can be easily re-coloured later? (At the moment, the images are created with colour in Photoshop or a similar package and then turned into a greyscale and exported from there before I even touch them)
With these greyscale images in place, what method makes colouring them with any colour possible? (They must retain the shading etc)

I've tagged this with HTML5 and Javascript, but any advise from other platforms would be helpful.

Edit: Here's an example greyscale output of the image on the left. I want to be able to restore it to the same colour, but also be able to blend it with other colours for different shades of skin.


texts:
With a game like "Farmville", there is both processing during gameplay, and when the user is offline (plants are always growing, for example). Many of the game maps elements depend on time.

Is there a trick to make this scale?  How can you possibly calculate 1 million users maps being modified every couple of seconds? Some of these games alert you, when things have changed, so it is not like they calculate everything when you login to the system.

How do you calculate game map changes, over time, when the user is not online?


texts: Speed up loading of png files (used for textures) in Android OpenGL Game

texts:
My game has a few texture atlases that need to be loaded (in my XHDPI folder they total 3.49MB) and on a top-end device they don't take that long to load, however on a low-end device they seem to take an age.

An example would be my old Samsung Galaxy Ace which uses the MDPI folder for it's resources (total: 1.51MB), this takes 16 seconds, which I personally consider far too long.

Originally, I had a separate atlas for each sprite, so I merged the majority of my atlases into one big atlas after reading that it may speed things up.

Unfortunately, it hasn't really made any difference to the load-speed.

This is how I'm loading my png files:

atlas = BitmapFactory.decodeResource(view.getResources(), R.drawable.atlasimage);

As the default load format is ARG_B8888, I though I'd attempt to load them in RGB565 as this is supposed to be quicker to load and render as well as take up less memory.

So I tried this:

BMFOptions = new BitmapFactory.Options();
BMFOptions.inDither=false;
BMFOptions.inPreferredConfig = Bitmap.Config.RGB_565;

atlas = BitmapFactory.decodeResource(view.getResources(), R.drawable.atlasimage, BMF Options);

Unfortunately, although this does reduce the quality of the image, it doesn't reduce the load time and yields no noticible performance increase.  Also, (and this may be expected), it doesn't reduce the memory footprint of my app.

So my question is how can I optimise this so that my png's are loaded quicker (rendering speed increase not being as important at the moment as load-speed).


texts: How can I generate a terrain heightmap from the perlin algorithm? I am trying to make a terrain generator (like World Machine). This is the source code I have for the perlin. The only thing that I can't figure out is how to use the perlin algorithm to generate a heightmap image.


texts: Mapping decibel range to linear audible intervals

texts:
I am working in an engine that encodes sound as decibels (dB). Let's assume the decibel range of human hearing is -60dB to 0dB.

Audibility is not linear across this range.

So my question is...

How does one map a decibel range to a set of numbers (for example, 1-10), such that each number corresponds to (roughly) one linear step up in audibility?


texts: What are good JS libraries for game dev?

texts:
If I decide to write a simple game both text and graphical (2d) what libraries would I use? (Assume we are using a HTML5 compatible browser)

The main things I can think of

Rendering text on screen
Animating sprites (using images/css)
Input (capturing the arrow keys and getting relative mouse positions)
Perhaps some preloading resource or dynamically loading resources and choosing order
Sound (but I am unsure how important this will be to me at first). Perhaps with mixing and chaining sounds or looping forever until stop.
Networking (low priority) to connect a user to another or to continuously GET data without multiple request (I know this exist but I don't know how easy it is to setup or use. But this isn't important to me. Its for the question).


texts:
Through development I've been running my 2D game (Monogame 3.6) on my windows laptop, which has some crummy integrated graphics card and an i5. Now I try my game on my gaming PC, which has a GTX 970 and also an i5 (a slightly better one), and the game runs slow as hell.

I'm at a complete and total loss here. Here's what I've tried to speed up the game, and it's still hovering around maybe 15 FPS:

Reducing the game from 3 or 4 spritebatch blocks to a single one
Removing ALL shader uniform changes, so that it only sets up the shader uniforms once and never changes them
Commenting out 100% of particle rendering code.
Removing my extra render target that I used for post process fx.

After all of this, making it about as simple as a Hello World renderer, and it's still dog slow. I'm dumbfounded. Codetrack profiler says 80% of my cpu time is inside of a function called DoDraw which seems to be XNA framework code. So I'm sure it's not the update logic, or sheer number of things rendering, etc. The time anything is taking pales in comparison to DoDraw. The stack looks like this:

Tick
DoDraw
Present
PlatformPresent

But I don't really understand what it's doing and why it's taking so long. Any tips, knowledge of rendering quirks, profiling tips, etc, anything appreciated.


texts: Unity: Can't access repeatDelay from StandaloneInputModule?

texts:
I have a very specific problem. I'm trying to change the repeatDelay variable within my StandaloneInputModule, but it's not coming up as a variable. All of the other variables come up when I use GetComponent<StandaloneInputModule>(), but not the one that I want. Is there something different about repeatDelay that I'm not seeing?

EDIT: I'm using the UnityEngine.EventSystems namespace too.


texts: Typical Method Of Building Puzzle Levels

texts:
I am designing a puzzle game for the iphone and was wondering as most puzzle games consist of the player progressing through multiple levels. You see for example Angry Birds has over 100 levels.

Once the basis of the game is made, how do developers typically go about building their levels?

Do they generally build them from scratch each one more or less, or work of their own template or have some other method which they use to tailor these levels?

I imagine building so many levels is a long process, certainly if building each one individually. Do they do this, or have a method which speeds it up once they have their basis?


texts: Using RPC's for movement of an object across a network

texts:
I've been building upon http://www.gamasutra.com/blogs/DarrelCusey/20130221/187128/Unity_Networking_Sample_Using_One_NetworkView.php At the moment when I spawn a sphere on the server it spawns on the clients aswell. On the server side I have two buttons, move left and move right. Ive been trying to get the movement to go across to the clients aswell but to no avail. The sphere moves on the server but nothing on the clients. Below is the code I have attempted, where have I went wrong with this? The debug line in SendSpherePosition outputs the spheres position perfect, but the position is not updating on the client, so is it a problem with the line below it "spawnedSphere.transform.position = spherePosition;"?

 if (Network.isServer && isSphereSpawned==true && closeOutExtras==false)
     {
         Debug.Log("the position of the sphere is: " + spawnedSphere.transform.position );
         //If called here sphere's continuously spawn on the client
         networkView.RPC("TellClientsToSpawnSphere", RPCMode.Others, null);
         //put this bool in just to have one spawn on the client, bad code, will need to change
         closeOutExtras = true;
     }

     if (Network.isServer && isSphereSpawned==true)
     {
         Debug.Log("the position of the sphere is: " + spawnedSphere.transform.position );
         if (lastLocalSpherePosition != spawnedSphere.transform.position)
         {
             networkView.RPC("SendSpherePosition", RPCMode.Others, spawnedSphere.transform.position);
             lastLocalPlayerPosition = spawnedSphere.transform.position;
         }
     }

 }

 [RPC]
 void SendSpherePosition(Vector3 spherePosition)
 {
     Debug.Log ("The sphere position is: " + spherePosition);
     spawnedSphere.transform.position = spherePosition;
 }

 [RPC]
 void TellClientsToSpawnSphere()
 {
     Instantiate (spawnedSphere);
 }


texts:
I have class "Button" with function

public void SetOnClickListener(UnityAction listener)
{
    btn.onClick.AddListener(listener);
}

I have class "A" with fllow code

void D()
{
    Button btn = new Button();
    btn.SetOnClickListener(new UnityAction(SomeFunction));
}
public void SomeFunction()
{
    Debug.Log("Some Function was called!");
}

And it doesn't work. But if I do next change->

void D()
{
    Button btn = new Button();
    btn.SetOnClickListener(new UnityAction(SomeFunction));
}
public static void SomeFunction()
{
    Debug.Log("Some Function was called!");
}

All work correctly. Why I must use static and can I not use it?


texts: Calculate the angle between two 3d vectors: Function always returns 89.1-89.9

texts:
I have my own 2d game and I am attempting to calculate the angle between 2 GameObjects.

My Problem: My function that is meant to calculate the angle(direction) between 2 Vector3's doesn't appear to be correctly calculating the angle. It always returns a value thats between 89.1 and 89.9, its never any other value.

What am I doing wrong? Can you help me to get my function to correctly calculate the angle between 2 Vector3's?

float getAngle(Vector3 p1, Vector3 p2) {

    // If p1 or p2 == Vector3.zero then this funciton wont work. What shd I do in this case?

    float coefI  = p1.x * p2.x;
    float coefJ  = p1.y * p2.y;
    float coefK  = p1.z * p2.z;
    float scalar = coefI + coefJ + coefK;
    float magnitude1 = p1.sqrMagnitude;
    float magnitude2 = p2.sqrMagnitude;

    Debug.Log (System.String.Format ("{0}, {1}, {2}, {3}, {4}, {5}", coefI, coefJ, coefK, scalar, magnitude1, magnitude2));
    return (Mathf.Acos ( scalar / (magnitude1 * magnitude2) ) * Mathf.Rad2Deg); // Always returns between 89.1 and 89.9 for some reason
}

void Update() {
    Debug.Log( getAngle (Input.mousePosition, transform.position) );
}


texts: How to render grid properly, especially over distance?

texts:
I'm drawing a grid, pretty much like one can see in the Unity editor itself or any 3D-editor, many 3D-related applications and some games. But it doesn't look pretty in my case.

I put a few random objects to make perspective more readable.

Please also see it full-size for clearer view on the artifacts at a distance.

How grid is rendered

Whole grid is one big plane.
There is texture representing one cell.
The cell is multiplicated by tiling.

How there are different line thicknesses on the picture?

It's just 3 planes (each with one grid) with different settings on top of each other. I could leave only one, but 3 grids demonstrate my problem better.

Additional details:

Mipmap is disabled (grid cells disappear very soon over distance when it's enabled).
Trilinear filtration and maximum aniso are set (looks worse otherwise).

My guess

I think over distance lines get to be thinner than a pixel, especially under shallow angle (hence “verticals” lines look better than “horizontal”.

Conclusion

Grid rendering is obviously done many times before me, so I presume it should be pretty much wide knowledge how to draw them prettily. I tried to google it, but any query formulation I tried led only to completely unrelated stuff. I have a bit of ideas what I can try, but I believe it would be reinventing the wheel.

P.S.: I'm using Unity engine, but I believe the engine is irrelevant.

Plane simple blurring suggested by user29244 and Thebluefish really makes huge difference:

Biggest lines are too blurry now, but it's irrelevant, because easy to fix.
Note that I had to enable mipmaping if you're trying to reproduce it.


texts: Gravity is really low when animation is added to a character

texts: Basically I added a animation to my character, applied root motion so he could move around, although the gravity somehow decreased alot, my character now descends slowly...


texts: Linking error when compiling Allegro example

texts:
I am currently learning about game development tools and decided to use Allegro and OpenGL for starters. I've run into some problems in getting examples to compile though. It seems the allergro.h library isn't linking correctly. Some web searching didn't help.

Here's my example code:

#include <stdio.h>
#include <allegro.h>

int main()
{
    allegro_init();
    //...
    return 0;
}
END_OF_MAIN();

I'm running this command to compile it:

g++ allegroTemplate.cpp -o allegroTemplate

This is the error I'm getting:

/tmp/ccbpAXIY.o: In function `main':
allegroTemplate.cpp:(.text+0x2a): undefined reference to `_install_allegro_version_check'
collect2: ld returned 1 exit status

I'm running this in Ubuntu.


texts: Tween animation with Universal Tween Engine LIbGDX

texts:
Let me preface by saying that I'm new to libgdx...

I have an animation that I'm currently drawing to the screen using:

game.batch.draw(flyAnimation2.getKeyFrame(elapsedTime, true), 200,200,0, 0, 124, 90, 1.0f, 1.0f, 90);

Where flyAnimation2 is:
   Animation flyAnimation2;

This works correctly.  I now want to use UniversalTweenEngine to tween it from one side of the screen to the other.

I can't find any decent documentation on how to achieve this affect using an Animation.  Any help would be appreciated!!


texts:
I am currently working on a game based on SFML and written in C++. For the HUD of the game I have a HUD class with a lot of different variables and methods. Basically most of the variables have a set and get method. We are talking about 14 variables currently and I am sure this will increase.

Example excerpts:

sf::Text m_AmmoText;
sf::Text m_ScoreText;

sf::Text getAmmoText();
sf::Text getScoreText();

void setAmmoText(sf::String text);
void setScore(sf::String text);

Questions

Optimize context is performance vs. code mantainability

1. Prototyp or Inheritance?

I searched the web and found the prototype pattern or the inheritance of classes as the most useful ones to apply. Since I never use both I am quite unsure which solution will have a positive impact on the code and performance. I am aware that with these few classes the performance impact is hardly measurable. It is more for practice and to get it right from the beginning. I started to re-write the code to apply inheritance but thought it might be better to ask the experts first.

Here is an example of the classes. Implementation of methods accordingly to read or write the variable (skipped here).

class HUD{
    protected:
        sf::Text m_Text;
    public:
        getText();
        setText();
}

class HudAmmo : public Hud {};
class HudScore : public Hud {};

So instead of hud.getAmmoText() I could use hudammo.getText().
I did not code the prototyping yet. But read a lot about its pros and cons on the internet. Suprisingly I could not find a clear direction since most examples I found were abstract. I tend to apply the prototyping pattern from what I understood so far mainly because of this post:

2. Alternative

Re-write the class and have only 1 set and get method which passes the context, e.g. hiscore or other solutions?


texts: Particles placed in the middle of the screen (OpenGL ES 2 / Android)

texts:
It seems like each of my particles is placed at (0, 0, 0) even though I'm setting different positions for each of them (debugger also confirms this). It must be something really silly that I'm missing. My intention is to paint 250 particles at random positions on the screen. Here's my code:

@Override
public void onDrawFrame(GL10 gl) {
    if(time++ == MAXTIME) {
        time = 0;
    }

    //my own helper methods
    GLUtils.sendBufferData(a_Position, 3, position);
    GLUtils.sendBufferData(a_Velocity, 3, velocity);
    GLUtils.sendBufferData(a_Offset, 1, offset);

    Matrix.setIdentityM(mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, camera.getViewMatrix(), 0, mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, camera.getProjectionMatrix(), 0, mMVPMatrix, 0);

    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    GLES20.glUniform1f(u_Time, time);

    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
    GLES20.glUniform1i(u_Texture, 0);

    GLES20.glDrawArrays(GLES20.GL_POINTS, 0, particlesCount); //particlesCount = 250
}

@Override
protected void initData() {
    float[] positions = new float[3 * count];
    float[] velocities = new float[3 * count];
    float[] offsets = new float[count];

    int index = 0;

    for(int i = 0; i < count; i++) {
        offsets[i] = MathUtils.random() * 60 + 20;

        positions[index] = MathUtils.random() * 2 - 1;
        velocities[index] = -0.025f;
        index++;

        positions[index] = MathUtils.random() * 2 - 1;
        velocities[index] = -0.035f;
        index++;

        positions[index] = 0;
        velocities[index] = 0;
        index++;
    }
    //my own helper method
    texture = GLUtils.loadTexture(mContext, R.drawable.snowflake);

    position = ByteBuffer.allocateDirect(positions.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
    velocity = ByteBuffer.allocateDirect(velocities.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
    offset = ByteBuffer.allocateDirect(offsets.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();

    position.put(positions).position(0);
    velocity.put(velocities).position(0);
    offset.put(offsets).position(0);
}

private static final String vertexShader() {
    return "" +
            "uniform mat4 u_MVPMatrix;\n" +
            "uniform float u_Lifetime;\n" +
            "uniform float u_CurrentTime;\n" +
            "\n" +
            "attribute vec4 a_Position;\n" +
            "attribute vec3 a_Velocity;\n" +
            "attribute float a_Offset;\n" +
            "\n" +
            "void main() {\n" +
            "    gl_PointSize = 10.0;\n" +
            "    gl_Position = u_MVPMatrix * a_Position;\n" +
            "}";
}

private static final String fragmentShader() {
    return "precision mediump float;\n" +
            "\n" +
            "uniform sampler2D u_Texture;\n" +
            "\n" +
            "void main() {\n" +
            "    gl_FragColor = texture2D(u_Texture, gl_PointCoord);\n" +
            "}";
}

Note: I deliberately deleted some lines from the vertex shader since I don't think they are relevant in this case.

Edit: It may be that gl_PointCoord is always set to 0. I'm looking into this now.


texts: SDL2 C++ How to make enemy move in random directions

texts:
How do i make an Enemy move in random directions?
I tried this but it doesnt work how i want it to.. thats why im asking what i need to do, to achieve that? (Pseudo code would be cool)

 void Enemy::Update()
{
    Timer += Timer->GetTimeElapsed();
    int Random = (rand() % 4);
    if (Timer >= 2.0f)
    {
        switch (Random)
        {
        case(0):
            m_xPos += 10.0f * Timer->tElapsed();
        case(1):
            m_xPos -= 10.0f  * Timer->tElapsed();
        case(2):
            m_yPos -= 10.0f  * Timer->tElapsed();
        case(3):
            m_yPos += 10.0f  * Timer->tElapsed();
        }
    }
}

Thank you

Edit: This is the movement i get so far.


texts: How do I dynamically load a smaller texture in Unity based on the screen size?

texts: I have a Unity application on windows phone which is having problems running on small devices because the HD textures are so huge. What is the best way to test and dynamically use a smaller version on a smaller or less powerful device?


texts: What is so special about directx 11's dynamic tessellation? Can't it be implemented by hand, and just render geometry tessellated by your own code using older versions of directx? What are the advantages of using dx11? Thank you!


texts:
I keep on getting segmentation fault each time I load fourth texture - what type of texture, I mean filename, does not matter. I checked value of GL_TEXTURES_STACK_SIZE which turned out to be 10 so quite more than 4, isn't it?

Here're code fragments:

funciton to load texture from png

static GLuint gl_loadTexture(const char filename[]) {
    static int iTexNum = 1;
    GLuint texture = 0;
    img_s *img = NULL;

    img = img_loadPNG(filename);
    if (img) {
        glGenTextures(iTexNum++, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, img->iGlFormat, img->uiWidth, img->uiHeight, 0, img->iGlFormat, GL_UNSIGNED_BYTE, img->p_ubaData);
        img_free(img); //it may cause errors on windows
    } else printf("Error: loading texture '%s' failed!\n", filename);

    return texture;
}

actual loading

static GLuint textures[4];

static void gl_init() {
    (...) //setting up OpenGL

    /* loading textures */
    textures[0] = gl_loadTexture("images/background.png");
    textures[1] = gl_loadTexture("images/spaceship.png");
    textures[2] = gl_loadTexture("images/asteroid.png");
    textures[3] = gl_loadTexture("images/asteroid2.png"); //this is causing SegFault no matter which file I load!
}

Any ideas?

Problem is present on both Linux and Windows.


texts: Alternatives to Component Based Architecture?

texts:
Usually when I develop a game I will use an architecture like what you see below. What other architectures are popular for simple game development? I'm concerned about having a narrow view of what exists out there for architectures beyond this. Is this an example of component-based architecture? Or is this something else? What would that look like? What alternatives exist?

public abstract class ComponentBase {

    protected final Collection<ComponentBase> subComponents = new LinkedList<ComponentBase>();

    private boolean enableInput;
    private boolean isVisible;

    protected ComponentBase(boolean enableInput, boolean isVisible) {
        this.enableInput = enableInput;
        this.isVisible = isVisible;
    }

   public void render(Graphics2D graphics) {
        for(ComponentBase gameComponent : this.subComponents) {
            if(gameComponent.isVisible()) {
                gameComponent.render(graphics);
            }
        }
    }

    public void input(InputData input) {
        for(ComponentBase gameComponent : this.subComponents) {
            if(gameComponent.inputIsEnabled()) {
                gameComponent.input(input);
            }
        }
    }

    ... getters/setters ...

    public void update(long elapsedTimeMillis) {
        for(ComponentBase gameComponent : this.subComponents) {
            gameComponent.update(elapsedTimeMillis);
        }
    }

}


texts: LWJGL int vertex attribute not working in shader

texts:
I'm trying to send an integer attribute to my GLSL shader. The shader receives the attribute as follows:

layout (location = 3) in int integer_value;

I'm creating the attribute as follows:

glBindBuffer(GL_ARRAY_BUFFER, this.integerValueVboId);
glBufferData(GL_ARRAY_BUFFER, integer_values_buffer, GL_STATIC_DRAW);
glVertexAttribPointer(3, 1, GL_INT, false, 0, 0);

this.integerValueVboId is a valid ID generated with all the other VBOs. integer_values_buffer is an IntBuffer confirmed to contain the correct integer values.

When I set one of the integer values to 1, the shader receives the integer value 1065353216, which I have found to be the value obtained when one interprets a float 1.0f as an integer value.


texts: where can I get people to create project with me?

texts: I've almost finished my studies. Actually I am looking for job to get experience but besides this I have a lot of free time. Could you tell me where can I (make relationship with ) find new people who also likes create new games or apps in java/c# and work together?


texts: How to properly format classes for JSON deserialization with JSON.net for Unity?

texts:
**UPDATE: This answer has been solved and this post updated to **

I am creating an inventory system and decided to keep a master list of all the items.  The goal is to use Newtonsoft's JSON.net to parse the item list and populate the database of items. The JSON item list looks like:

JSON

{
"Ingredients":
    [

    ],
"Consumables":
    [
            {
            "ID" : "TP_Small",
            "Icon" : "Sprites/porridge.png",
            "Name" : "Small Tan Pill's Porridge",
            "Consumable" : true,
            "Cooldown": 0,
            "Duration": 3,
            "Effect Description" : "Restores 100 health.",
            "Description" : "A hearty drinkable meal from everyone's favorite hypercellulose gelatin timelord!!!",
            "SFX": "{eb4e9ad8-c6ac-414f-8d5e-c3d012ca6ae6}",
            "Bonuses" : {
                "HP": 100,
                "Stamina": 100,
                "Tolerance": 20,
                "Attack": 4
                }
            }
    ],

"Concoctions":
    [

    ],
"Equipment":
    [

    ],
"Abilities" :
    [

    ]
}

And this is the structure of the classes we are using to match the JSON:

Classes

[System.Serializable]
public class Items
{
    public List<ItemBase> Ingredients;
    public List<ItemBase>Consumables;
    public List<ItemBase>Concoctions;
    public List<ItemBase>Equipment;
    public List<ItemBase>Abilities;
}

[System.Serializable]
public class ItemBase
{
    public string ID;
    public string Icon;
    public string Name;
    public bool Consumable;
    public int Cooldown;
    public int Duration;
    public string EffectDescription;
    public string Description;
    public string SFX;
    public StatBonus Bonuses;
}

[System.Serializable]
public class StatBonus
{
    public int HP;
    public int Stamina;
    public int Tolerance;
    public int Attack;
 }

The deserialization code:

TextAsset json = Resources.Load<TextAsset>(path);

    itemList = new Items();

    itemList.Abilities = new List<ItemBase>();
    itemList.Concoctions = new List<ItemBase>();
    itemList.Consumables = new List<ItemBase>();
    itemList.Equipment = new List<ItemBase>();
    itemList.Ingredients = new List<ItemBase>();

    itemList = JsonConvert.DeserializeObject<Items>(json.text);

This code now works as intended!


texts: Can somebody explain this behavior in pygame?

texts:
I have an image that I'm rotating and moving

And when the rotation angle is negative the image moves as expected.

But when the angle is positive it moves it's origing point to the left

Can anybody explain this behavior, and how to solve it?

Here is the code

import pygame, sys
import math

screen = pygame.display.set_mode((700, 400))
wrench = pygame.image.load('prueba.bmp')
white = (255,255,255)

ox = 20
oy = 32
running = True
posX = 100 - ox
posY = 100 - oy

pygame.init()
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running=0
        screen.blit(wrench, (posX, posY))
    if(pygame.time.get_ticks() <= 20000):
        screen.fill(white)
        t = pygame.time.get_ticks() / 1000
        ang = math.degrees(math.pi / 2 * math.cos(math.pi * t))
        #ang = math.pi / 2 * math.cos(math.pi * t)
        print(ang)
        posX = 100 + (50 * math.cos(math.pi * t)) - ox
        posY = 100 + (20 * math.sin(math.pi * t)) - oy
        rotated_wrench = pygame.transform.rotate(wrench, ang)
        screen.blit(rotated_wrench, (posX, posY))
    pygame.display.flip()


texts:
I want to set a time limit for scrolling text in OpenGL & GLUT. How can I stop scrolling at 250? Here is my code. I try with the if condition but it's not working. The scrolling is not stopping in 250, it scrolls infinitely.

#include<fstream>
#include<iostream>
#include<stdlib.h>
#include<glut.h>

using namespace std;
float yr = 0;
float translate =0.0f, angle = 0.0f;

//identifiers
void introscreen();
void screen();

void specialKey(int key, int x, int y) {
    switch (key) {
    case GLUT_KEY_UP:
        translate += 1.0f;
        break;
    case GLUT_KEY_DOWN:
        translate -= 1.0f;
        break;
    case GLUT_KEY_LEFT:
        angle += 1.0f;
        break;
    case GLUT_KEY_RIGHT:
        angle -= 1.0f;
        break;
    }
    glutPostRedisplay();
}
void SpeedText() {

    GLfloat y;
    GLfloat y2;
    GLfloat fSize[5];
    GLfloat fCurrSize;
    fCurrSize = fSize[2];
    for (y = 0.0f; y <= 250.0f + yr; y += 5.0f) {
        glLineWidth(fCurrSize);
        glBegin(GL_LINES);
        glVertex3f(-200.0f, y + translate, 0);
        glVertex3f(-180.0f, y + translate, 0);
        glEnd();
        fCurrSize += 1.0f;
        introscreen();
    }
    if (y + translate >= 50) {
        y == 50;
    }
    }
void renderbitmap(float x1, float y1, void *font, char *string) {
    char *c;
    glRasterPos2f(x1, y1);
    for (c=string; *c != '\0'; c++) {
        glutBitmapCharacter(font, *c);
    }
}

void introscreen(void) {
    glColor3f(0, 1, 0);
    char buf[10] = { '\0' };
    for (int row = 0.0f; row <= 250+yr; row +=5.0f) {
        sprintf_s(buf,"%d", row);
        renderbitmap(-220, (translate +row), GLUT_BITMAP_TIMES_ROMAN_24, buf);
    }
 }
int main(int arg, char** argv) {
    glutInit(&arg, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(width, height);
    glutInitWindowPosition(50, 100);
    glutCreateWindow("HUD Lines");
    display();
    SpeedText();
    glutSpecialFunc(specialKey);
    glutMainLoop();
    return 0;
}


texts: Position of Gameobject Changes When Hit Play Button

texts: I have a 3D Humanoid model. When I press play button, suddenly position of model  changes and collider doesn't match with model.


texts: Light on every model and not in the whole scene

texts:
I am using a custom shader and try to pass the effect on my Models like that:

foreach (ModelMesh mesh in Model.Meshes)
{
       foreach (ModelMeshPart part in mesh.MeshParts)
       {
           part.Effect = effect;
       }
       mesh.Draw();
}

My only issue is that every Model now has its own light source in it. Why is this happening and is this a problem of my shader?

Edit:

These are the parameters passed to the shader:

      private void Get_lambertEffect()
            {
                if (_lambertEffect == null) _lambertEffect = Engine.LambertEffect;

                //Lambert technique (LambertWithShadows, LambertWithShadows2x2PCF, LambertWithShadows3x3PCF)
                _lambertEffect.CurrentTechnique = _lambertEffect.Techniques["LambertWithShadows3x3PCF"];
                _lambertEffect.Parameters["texelSize"].SetValue(Engine.ShadowMap.TexelSize);

                //ShadowMap parameters
                _lambertEffect.Parameters["lightViewProjection"].SetValue(Engine.ShadowMap.LightViewProjectionMatrix);
                _lambertEffect.Parameters["textureScaleBias"].SetValue(Engine.ShadowMap.TextureScaleBiasMatrix);
                _lambertEffect.Parameters["depthBias"].SetValue(Engine.ShadowMap.DepthBias);
                _lambertEffect.Parameters["shadowMap"].SetValue(Engine.ShadowMap.ShadowMapTexture);

                //Camera view and projection parameters
                _lambertEffect.Parameters["view"].SetValue(Engine._camera.ViewMatrix);
                _lambertEffect.Parameters["projection"].SetValue(Engine._camera.ProjectionMatrix);
                _lambertEffect.Parameters["world"].SetValue(
                Matrix.CreateScale(Size) *
                world
            );
                //Light and color
                _lambertEffect.Parameters["lightDir"].SetValue(Engine._sourceLight.Direction);
                _lambertEffect.Parameters["lightColor"].SetValue(Engine._sourceLight.Color);
                _lambertEffect.Parameters["materialAmbient"].SetValue(Engine.Material.Ambient);
                _lambertEffect.Parameters["materialDiffuse"].SetValue(Engine.Material.Diffuse);
                _lambertEffect.Parameters["colorMap"].SetValue(ColorTexture.Create(Engine.GraphicsDevice, Color.Red));

            }

Image:


texts: Pseudocode for calculating per vertex normals for a trianglestrip mesh

texts:
I have a terrain that is defined as a trianglestrip mesh. Now I'm trying to calculate the normals of each vertex but I've realised that my normal way of calculating vertex normals only works with triangle meshes. I'm finding it hard to wrap around my head how to get the triangles from trianglestrip to calculate the normal in code. I can imagine it but just can't understand how that translates into code.

Can someone help me with some pseudocode or anything of that matter that demonstrates how I could cycle an array that contains indices used in a trianglestrip to calculate the normals?

EDIT:

I ended up finding this answer on stackoverflow and it looked like a very efficient and easy way to generate normals from a heightmap: https://stackoverflow.com/questions/49640250/calculate-normals-from-heightmap/49640606?noredirect=1#

The question defines the point and it's neighbours as follows for clarity. O being the vertex we're calculating a normal for:

  T
L O R
  B

Having translated it to my own cordinate system (right handed because of opengl), I ended up with the calculation of a normal of a vertex as:

Vec3 normal = Normalize(Vec3((R-L)/2, 1.0f, (B-T)/2));

I implemented that. Here's the constructor for a terrain in my code (fair warning, I am writing my own engine with its own math library. You should be able to infer the meanings of some things by their names though):

Terrain :: Terrain(unsigned int size)
{
    unsigned int xSegments = size;
    unsigned int ySegments = size;

    srand(time(NULL));
    m_NoiseMap = CreateScope<NoiseMap>(xSegments + 1, ySegments + 1);
    m_NoiseMap->GenerateNoise(rand() % 9999, 25, 0.015, 0.52, Vec2(0.4), 4);

    float dX = (float)size  / xSegments;
    float dY = (float)size / ySegments;

    auto heightMap = *m_NoiseMap;

    for (unsigned int y = 0; y <= ySegments; ++y)
    {
        for (unsigned int x = 0; x <= xSegments; ++x)
        {
            auto height = heightMap[x][y];
            auto position = Vec3(dX * x * 2.0f - 1.0f, height, dY * y * 2.0f - 1.0f);

            Positions.push_back(position);
            UV.push_back(Vec2(dX * x, 1.0f - y * dY));

            float heightR, heightL, heightU, heightD = height;

            if (y > 0)
                heightU = heightMap[x][y - 1];

            if (x > 0)
                heightL = heightMap[x - 1][y];

            if ( y < ySegments)
                heightD = heightMap[x][y + 1];

            if (x < xSegments)
                heightR = heightMap[x + 1][y];

            Normals.push_back(Normalize(Vec3((heightR - heightL)  / 2, 1.0f, (heightD - heightU) / 2)));
        }
    }

    bool oddRow = false;

    for (int y = 0; y < ySegments; ++y)
    {
        if (!oddRow)
        {
            for (int x = 0; x <= xSegments; ++x)
            {
                Indices.push_back(y       * (xSegments + 1) + x);
                Indices.push_back((y + 1) * (xSegments + 1) + x);
            }
        }
        else
        {
            for (int x = xSegments; x >= 0; --x)
            {
                Indices.push_back((y + 1) * (xSegments + 1) + x);
                Indices.push_back(y       * (xSegments + 1) + x);
            }
        }
        oddRow = !oddRow;
    }

    Topology = TRIANGLE_STRIP;
    Finalize();
}

Unfortunately, when I do this, I get this as the result once I'm done lighting the mesh:

Which just looks random if you ask me. I've set the normal to be flat in the shader as I'm trying to make low poly terrain and do not need smooth shading. Anyone have any clues where I'm going wrong?

Thank you


texts: Parsing .OBJ to fit the gldrawelements() call. c++/opengl

texts:
I'm struggling trying to get this to work like it should. Ive been able to make an obj loader that fits the glDrawArrays() call, with uv and facenormals, but when trying to modify it to fit glDrawElements() Im at a loss.

This is the code I have this far, the function takes the addresses of the vectors to be filled:

void objload3(string filename, vector<glm::vec3>&vertices, vector<glm::vec2>&texcords, vector<glm::vec3>&normals)
{
    size_t vertsize = 0; size_t texsize = 0; size_t normalsize = 0; size_t facesize = 0;  //ref size containers

    string line; string token;
    std::ifstream file(filename);

    if (file.is_open())
    {
        while (getline(file, line)) //count size
        {
            if (line.compare(0, 2, "v ") == 0)++vertsize;
            else if (line.compare(0, 2, "vt") == 0)++texsize;
            else if (line.compare(0, 2, "vn") == 0)++normalsize;
            else if (line.compare(0, 2, "f ") == 0)++facesize;
        }file.close();
    }

    //set size
    vector <glm::vec3>verticeref(vertsize);
    vector <glm::vec2>texkoordref(texsize);
    vector <glm::vec3>normalref(normalsize);

    vector<string>points(facesize * 3);

    //index filling counters
    size_t vcount = 0; size_t vtcount = 0; size_t vncount = 0; size_t fcount = 0; size_t refcount = 0;

     //fill reference vectors
    file.open(filename);
    if (file.is_open())
    {
        while (getline(file, line))
        {
            if (line.compare(0, 2, "v ") == 0) {
                istringstream s(line.substr(2));
                glm::vec3 v; s >> v.x; s >> v.y; s >> v.z;
                verticeref[vcount++] = v;
            }

            else if (line.compare(0, 2, "vt") == 0) {
                istringstream s(line.substr(2));
                glm::vec2 v; s >> v.x; s >> v.y;
                texkoordref[vtcount++] = v;
            }

            else if (line.compare(0, 2, "vn") == 0) {
                istringstream s(line.substr(2));
                glm::vec3 v; s >> v.x; s >> v.y; s >> v.z;
                normalref[vncount++] = v;
            }

            else if (line.compare(0, 2, "f ") == 0) {
                line.erase(0, 2);
                istringstream is(line);
                while (getline(is, token, ' '))points[fcount++] = token;
            }
        }file.close();
    }

    vector<int>indexref(3*points.size()); //faces allocation

//clean up faces information, convert to int
for (unsigned int a = 0; a <points.size(); ++a) {
    stringstream is(points[a]);
    while (getline(is, token, '/')) { indexref[refcount++] = stoi(token); }
    is.clear();
}

at this point, I would do this to fit it with the glDrawArrays() call:

vertices.resize(points.size());
texcords.resize(points.size());
normals.resize(points.size());

refcount = 0; //keep track of fill

for (size_t fillcount = 0; fillcount < points.size(); ++fillcount)
{
    vertices[fillcount] = verticeref[indexref[refcount++] - 1];
    texcords[fillcount] = texkoordref[indexref[refcount++] - 1];
    normals[fillcount] = normalref[indexref[refcount++] - 1];
}

But this fill doesnt take account of all the duplicate vertices, nor does it create an index. Im having problems understanding the logic behind the gldrawarrays call, and how to easily make an index and list of vertices/uv/normals to fill the vbos with.

Seems like something the 3Dmodel tool should do, but it doesnt? I cant juse use the list of faces already in obj export?

Some clarification would be much appreciated.