texts: Draw Rectangle To All Dimensions of Image

texts:
I have some rudimentary collision code:

public class Collision {
    static boolean isColliding = false;
    static Rectangle player;
    static Rectangle female;

    public static void collision(){
        Rectangle player = Game.Playerbounds();
        Rectangle female = Game.Femalebounds();

        if(player.intersects(female)){
            isColliding = true;
        }else{
            isColliding = false;
        }
    }
}

And this is the rectangle code:

public static Rectangle Playerbounds() {
    return(new Rectangle(posX, posY, 25, 25));
}

public static Rectangle Femalebounds() {
    return(new Rectangle(femaleX, femaleY, 25, 25));
}

My InputHandling class:

public static void movePlayer(GameContainer gc, int delta){
    Input input = gc.getInput();

    if(input.isKeyDown(input.KEY_W)){
        Game.posY -= walkSpeed * delta;
        walkUp = true;

        if(Collision.isColliding == true){
            Game.posY += walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_S)){
        Game.posY += walkSpeed * delta;
        walkDown = true;

        if(Collision.isColliding == true){
            Game.posY -= walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_D)){
        Game.posX += walkSpeed * delta;
        walkRight = true;

        if(Collision.isColliding == true){
            Game.posX -= walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_A)){
        Game.posX -= walkSpeed * delta;
        walkLeft = true;

        if(Collision.isColliding == true){
            Game.posX += walkSpeed * delta;
        }
    }
}

The code works partially. Only the right and top side of the images collide. How do I correct the rectangle so it will draw on all sides?


texts: How to control which path a unit will take?

texts:
This might be a really easy solution that I probably just do not know due to lack of experience so thanks for any and all the help. TLDR at bottom of post.

I'm still learning Unity / C# and I am following Brackey's Tower Defense tutorial series while adding my own twist.
The tutorials use levels with only 1 available path for units to walk along. However, the game I am currently developing has 3 separate paths that units can walk along.

Essentially, the game is similar to the mobile game Clash Royale with 3 lanes except it is also a tower defense.

Here is the current layout:

The different lanes are empty gameObject labeled as Path1 (red), Path2 (blue), and Path3 (green).
The nodes laid out in each path are all children objects of their respective path.

Each of the parent path objects contain the following script:

public class Waypoints : MonoBehaviour
{
    public static Transform[] points;

    private void Awake()
    {
        points = new Transform[transform.childCount];
        for (int i = 0; i < points.Length; i++)
        {
            points[i] = transform.GetChild(i);
        }
    }
}

Now, following the tutorial, I have also successfully added an enemy that contains this EnemyMovement script:

public class EnemyMovement : MonoBehaviour
{
    public float speed = 10f;

    private Transform target;
    private int waypointIndex = 7;

    void Start()
    {
        target = Waypoints.points[7];
    }

    void Update()
    {
        Vector3 dir = target.position - transform.position;
        transform.Translate(dir.normalized * speed * Time.deltaTime);

        if(Vector3.Distance(transform.position, target.position) <= 0.2f)
        {
            GetNextWaypoint();
        }
    }

    void GetNextWaypoint()
    {
        if(waypointIndex <= 0)
        {
            Destroy(gameObject);
            return;
        }

        waypointIndex--;
        target = Waypoints.points[waypointIndex];
    }
}

Now, as it currently stands, whenever I have an enemy present on the field, it will successfully run down path2 (blue nodes). However, it will ONLY run down path2. I would like to be able to decide which path the enemy will take. Eventually, the enemy's actions will be decided by an Enemy AI.

The player will also be able to spawn units and will be able to decide which path the unit will travel.

So to reiterate:

TL;DR: Following Brackey's Tower Defense tutorial. Currently, enemy will always default to path2. I need to figure out how to have control over which path, out of 3 options, an enemy or friendly unit will take.


texts:
I'm developing a simple racing game, using Unity.
I've created a road simply applying a texture (asphalt) to a terrain .
Is it possible (and how to do) to mark that roard with an invisible marker to identifiy that as a road (so i can make appears bonus, or others similar things) ?
Which is the approach used in a racing game to accomplish that task ?
Please, don't tell me "buy a Roads assets" because i want to understand the basics, the main concept.

Thanks


texts: What is the proper way to instantiate multiple objects from a script while in the editor in Unity?

texts:
I would like to, for example, be able to spawn a wall of stacked boxes and be able to play with the number of boxes in each dimension in the editor (previously I would be instantiating these at runtime, but it is annoying to not be able to see these in the editor).

Currently I am using a bit of a work around, I am using the OnValidate method to achieve this, but its a bit of a bodge and my instantiated items do not spawn in play mode, I get the following error on play:
MissingReferenceException: The object of type 'Lattice' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Lattice.<OnValidate>b__8_0 () (at Assets/Lattice.cs:22)
UnityEditor.EditorApplication.Internal_CallDelayFunctions () (at /home/bokken/buildslave/unity/build/Editor/Mono/EditorApplication.cs:346)

Here is the script I am currently using:
public class Lattice : MonoBehaviour
{
    public int nX=1, nY=1, nZ=1;
    public float offsetX=1, offsetY=1, offsetZ=1;
    public GameObject item;

    // Validate called only in editor and only on variable change
    void OnValidate()
    {
        Clean(); // remove old items
        UnityEditor.EditorApplication.delayCall+=()=>
        {
            spawnBox3Grid(item, transform, nX, nY, nZ, offsetX, offsetY, offsetZ);
        };
    }

    void Clean()
    {
        foreach(Transform childT in transform)
        {
            UnityEditor.EditorApplication.delayCall+=()=>
            {
                //Debug.Log(childT.gameObject.name);
                DestroyImmediate(childT.gameObject);
            };
        }
    }

    void spawnBox2Grid(GameObject obj, Transform parent, Vector3 startingPos, int nItemsY, int nItemsZ, float zOff=1.0f, float yOff=1.0f, int k=0)
    {

        Vector3 boxPos = startingPos + new Vector3(0, yOff/2,-zOff*nItemsZ/2);
        Vector3 zOffset = new Vector3(  0, 0, zOff);
        Vector3 yOffset = new Vector3(  0, yOff, 0);

        for (int j=0; j<nItemsY; j++)
        {
            for (int i=0; i<nItemsZ; i++)
            {
                GameObject instance = Instantiate(obj, boxPos, Quaternion.identity, parent);
                instance.name = string.Format( "obj_{0}_{1}_{2}", i, j, k);
                instance.transform.localPosition = boxPos;
                instance.transform.localRotation = Quaternion.identity;

                boxPos+=zOffset;
            }
            boxPos-=nItemsZ*zOffset;
            boxPos+=yOffset;
        }

    }

    void spawnBox3Grid(GameObject obj, Transform parent, int nItemsX, int nItemsY, int nItemsZ, float xOff=1.0f, float yOff=1.0f, float zOff=1.0f)
    {

        Vector3 xOffset = new Vector3(  xOff,0, 0);
        Vector3 boxPos = new Vector3(-xOff*nItemsX/2,0,0);
        for (int k=0; k<nItemsX; k++)
        {
            spawnBox2Grid(obj, parent, boxPos,nItemsY,nItemsZ, yOff, zOff, k);
            boxPos += xOffset;
        }

    }

}

This YouTube video is probably closer to what I want, but I don't entirely understand it and was hoping there was a simpler way.
Edit:
Some extra context:
Delaying the DestroyImmediately calls seems to be the only way to delete objects from inside OnValidate and if I don't delay the Instantiate calls I get SendMessage cannot be called during Awake, CheckConsistency, or OnValidate.
Edit 2:
I guess I can use this code for previewing in the editor then use a scriptable object to store the parameters of my Lattice objects and then re-instantiate things at runtime? But that error that I'm getting; is it trying to run OnValidate just before play? (When presumably, the things I've instantiated aren't stored permanently so the lattice object is lost?) There has got to be a cleaner way of doing this...


texts: I am looking for a way to track the duration of a key press in gamemaker. I was looking into alarm functions, but I figured there's a more elegant way. How can I track the duration of a keypress?


texts: How should I setup my Minecraft-like world rendering for the best performance?

texts:
I want to know what technique will give me most fps in game. I have minecraft-like world and I need to display it. Now I have only one cube, created as VBO and if i need to display cube I just display it. But now I want to know what will be faster:

Create for each cube type VBO (even for each side of it) or to create new VBO each frame for whole mesh to display?

I am very new to subject so if there are other faster techniques let me know. Thanks in advance.


texts: multiple flash timeline animations with actionscript

texts:
I am not new to AS3 and Flash but new to Flash timeline animations and controlling them with AS3. Had posted a similar question last week but the solution did not work. Hope someone could help me out here.

I am trying to control two different animations separately for one of my horse gameobjects inside the timeline through AS3.

For now, I have inserted really basic keyframes that hold all my animation frames. I have labelled them appropriately. Please look at the image below. These are not full animations, for now I am just playing around and testing it out.

I have named all the frames labels like "startwalk" "endwalk" "startTurnBack" and so on..

Now I want to control these animations and play them individually using AS3. I have added an enter_frame listener and started with a basic code as below but it does not seem to be working.

// this is the Event.ENTER_FRAME named gameLoop
private function gameLoop(event : Event) : void {
            trace(" current label " +horseTwo.currentLabel);
            var currLabel:String = horseTwo.currentLabel;
            var next:String;
            next = currLabel;
            horseTwo.gotoAndPlay(next);
            if(currLabel == "endwalk"){
                horseTwo.stop();
            }
        }

Nothing gets played. But if I do horseTwo.play(), it plays the animation throughout which is not what I want. I want to be able to control the keyframes via labels separately each for Walk, TurnBack and few more animations. Anyone got any ideas?


texts:
Possible Duplicate:
  How do I calculate the angle of the slope at a point on a 2D bitmap terrain?

I am planning to make a platform game with my own little engine and I need to know how to detect the angle of a slope. Any help is appreciated.


texts: Explain this line segment intersection code

texts:
I've been reading this article on pathfinding over polygon meshes using line-of-sight, and in the article are several code snippets. One of them, the one I'm trying to understand, is a simple function that determines whether two line segments intersect.

Here is that function from the article (in C#, though that isn't important to me):

public static bool LineSegmentsCross(Vector2 a, Vector2 b, Vector2 c, Vector2 d)
{
    float denominator = ((b.X - a.X) * (d.Y - c.Y)) - ((b.Y - a.Y) * (d.X - c.X));

    if (denominator == 0)
    {
        return false;
    }

    float numerator1 = ((a.Y - c.Y) * (d.X - c.X)) - ((a.X - c.X) * (d.Y - c.Y));

    float numerator2 = ((a.Y - c.Y) * (b.X - a.X)) - ((a.X - c.X) * (b.Y - a.Y));

    if (numerator1 == 0 || numerator2 == 0)
    {
        return false;
    }

    float r = numerator1 / denominator;
    float s = numerator2 / denominator;

    return (r > 0 && r < 1) && (s > 0 && s < 1);
}

Without any explanation, I assume that the function accepts two line segments, a-b and c-d. I know the first part checks whether the two lines are parallel, in which case they don't intersect. After that, I'm not sure. I suspect the next bit checks whether the two segments are out of range of each other? The code talks about numerators and denominators, so maybe it's dealing with slope comparisons?

In any case, I'd like to understand the math used here for determining line intersections. I know there's an algorithm that this code is following, but I don't know what it is. How does the formula used in the first part determine that the lines are parallel? I know it works, but why does it work? And what does the function do after that? Why?

I'd much rather understand how the code works, and then write my own code from that knowledge, than just blindly copy someone else's code.


texts: How can I downsample a texture using FBOs?

texts:
I am rendering a scene to FBO as my render target whose size is 8 times the size of the orignal screen in OpenGL. Now i wan to downsample the texture generated by FBO to the size of the screen so as to achieve spatial anti aliasing. How do i achieve the down sampling ? Please provide implementation details.
Note : If there is a better way of doing anti aliasing in FBOs please mention that too. I am trying to remove the aliasing in the image attached below.


texts:
Take for example the first game loop from this question. A similar code is used in Minecraft (at least in older versions). I understand the concept and how this loop works in principle. But there is something I'm wondering about for a long time now. There are 20 tps (ticks per second) in Minecraft for example. There can be more fps (frames per second) than tps because the game loop renders as many frames as possible in the time which is left between the ticks. It's also clear to me, that one can do "partial ticks" or interpolations for each frame between the ticks to make the game smoother. This is actually the reason why there should be more fps than tps. Without the interpolations each frame between the ticks would be exactly the same.
Now suppose I write a game with 20 tps (50 ms (milliseconds) period) and an expected tick time of 40 ms as an extreme example. The expected tick time is the time, which the tick() function takes on average. Then there are 10 ms left each tick for rendering on average. Suppose rendering is very fast and the game still reaches 60 fps. However, the game wouldn't be smooth in this case because there are always long time intervals of about 40 ms, where no frame is rendered.
Of course I know that this is an extreme example and one would try to avoid such high tick times if possible. However, I want to know if there is a commonly used solution for this problem? Unfortunately I can't find any resources about this topic or this specific question.
I've come up with these ideas to solve this problem: One could try to ...

... render frames based on the current number of fps and buffer the frames for a while, to show them more frequently and smooth.
... tick and render on different threads. However, this has the disadvantage that one has to care about thread safety. The render thread must get or copy the data to show in a valid state somehow. This seems very inefficient and complicated.

Is there (another) common way to do this in game development?


texts: How do you transition to playing in XNA?

texts: I have two classes in my game, a Main Menu and the main playing screen. How can I swap through classes? E.g I click on "New Game" in the menu class and it changes it too the Game class.  A transition animation explanation would be nice.


texts:
I'm trying to figure out how to accurately capture the state of the web app by a URL, similar to something like https://jsfiddle.net/, where they create https://jsfiddle.net/foobar123 a custom ID for the code you load, and you can share that with anyone and they can run the code. However, it's not a live, interactive thing, so it makes sense to do it that way.

But I'm wondering what games do. I don't really play games so I am not aware how browser-based games use the URL. I'm interested to know if, when you want to start back your game (I'm imagining WoW, though I've never played it), you just go to wow.com and click "start" or "join", and there is no URL involved at all. Or perhaps instead of that, you go to wow.com/123foobar to go to your last saved state, and it loads up the environment as it last was.

I'm not wondering for WoW specifically, just generally any game, if they use the URL to persist state, and if so, how (roughly speaking). Some simpler games like agar.io don't seem to use the URL; if you refresh, you lose your spot and have to start over.

I'm not really sure how a game could save the dynamically evolving state in a URL, which is why I'm interested to see if any of them do.

Another related example is a Collaborative Markdown Editor. I don't know if they dynamically change the URL though to reflect the state, I doubt it.


texts: Implementing GDPR compliance for multiple different ad networks

texts:
I'm creating a Unity game that uses admob mediation to show rewarded ads. I'm using about 5-10 different ad networks.
How do I implement GDPR compliance for EU users?
I tried following some online tutorials, but none of them had content showing getting GDPR consent for multiple networks.
How can I modify this script to correctly get compliance where needed for all of my ad networks?
public class Mediation : MonoBehaviour
{
 string Video_Ad_Id = "ca-app-pub-3940256099942544/5224354917";
 private RewardedAd rewardedAd;
 public Button reviveBtn;

 void Start()
 {
    MobileAds.Initialize((initStatus) =>
    {
        Dictionary<string, AdapterStatus> map = initStatus.getAdapterStatusMap();
        foreach (KeyValuePair<string, AdapterStatus> keyValuePair in map)
        {
            string className = keyValuePair.Key;
            AdapterStatus status = keyValuePair.Value;
            switch (status.InitializationState)
            {
                case AdapterState.NotReady:
                    // The adapter initialization did not complete.
                    MonoBehaviour.print("Adapter: " + className + " not ready.");
                    break;
                case AdapterState.Ready:
                    // The adapter was successfully initialized.
                    MonoBehaviour.print("Adapter: " + className + " is initialized.");
                    break;
            }
        }
    });

    RequestRewardBasedVideo();
}

void Update()
{
    if (rewardedAd.IsLoaded())
    {
        reviveBtn.interactable = true;
    }
}

I'm not sure where to ask for consent as I'm using multiple ad networks and not just admob. In the documentation, there is this line of code:
AdRequest request = new AdRequest.Builder().AddExtra("npa", "1") .Build();

Where do I add this in the script above and how do I ask for consent for multiple networks, like Chartboost, Adcolony, ironSource etc?
EDIT
I have added the following code to the mainmenu script which loads up when the game starts.
public GameObject GDPR_Popup;
void Start()
{
    Invoke("CheckForGDPR",.25f);
}

void CheckForGDPR()
{
    if (PlayerPrefs.GetInt("npa", -1) == -1)
    {
        GDPR_Popup.SetActive(true);
    }
}

public void OnUserClickAccept()
{
    PlayerPrefs.SetInt("npa", 0); //this is for google admob
    AdColonyAppOptions.SetGDPRConsentString("1");
    AppLovin.SetHasUserConsent(true);
    GDPR_Popup.SetActive(false);
}

public void OnUserClickCancel()
{
    PlayerPrefs.SetInt("npa", 1);//this is for google admob
    AdColonyAppOptions.SetGDPRConsentString("0");
    AppLovin.SetHasUserConsent(false);
    GDPR_Popup.SetActive(false);
}

Would something like this work as I'm not sure how to test this?
Also, how to initialize the ad networks only when the user has accepted or canceled GDPR option(this I believe was mentioned in the google admob mediation documents but there was no code sample given).
Can someone please help?


texts: Can networking be platform independent in a libgdx game?

texts: LibGDX supports Desktop (Windows, Linux and Mac), Android and web applications. Can i code the network part of an online game without taking care of what kind a of application i'm running? i.e coding the network engine interdependently of the application type.


texts:
In the Start of my scenes I call the method that downloads the assetBundles for that scene. The problem is that it only downloads the first assetBundle from the list, the second does not download it. My code is:

Note: The Debug that shows the url shows the correct url both times, first http://mihost.com/assetbundles/asset1 and then http://mihost.com/assetbundles/asset2.
However, in the Debug that shows the assets 'added' in both cases it shows the name only of those in asset1

public virtual IEnumerator LoadBundleFromServer()
{

var AssetPathOnServer = "http://mihost.com/assetbundles/"

var assetBundleNames = new List<string>();
assetBundleNames.Add("asset1");
assetBundleNames.Add("asset2");

    for (int i = 0; i < assetBundleNames.Count; i++)
    {
        var currentAssetBundleName = assetBundleNames[i];
        var url = AssetPathOnServer + currentAssetBundleName;
        Debug.Log("url: " + url);

        var request = UnityWebRequestAssetBundle.GetAssetBundle(url);
        yield return request.SendWebRequest();
        if (!request.isHttpError && !request.isNetworkError)
        {
            var asseBundle = DownloadHandlerAssetBundle.GetContent(request,);

            Debug.Log("count assets: " + AssetNames.Count);

            for (int j = 0; j < AssetNames.Count; j++)
            {
                string assetName = AssetNames[j];
                AssetBundleRequest asset = asseBundle.LoadAssetAsync<AudioClip>(assetName);
                yield return asset;
                AudioClip myClip = asset.asset as AudioClip;
                if (!assetDictionary.ContainsKey(assetName))
                {
                    assetDictionary.Add(assetName, myClip);
                }
                Debug.Log("added: " + assetName);
            }
            asseBundle.Unload(false);
        }
        else
        {
            //TODO: aqui hay que mostrar un error
            Debug.LogErrorFormat("error request [{0}, {1}]", url, request.error);
        }
    }
}

public abstract List<string> AssetNames
{
    get;
}


texts: Doing imagemagick like stuff in Unity (using a mask to edit a texture)

texts:
There is this tutorial in imagemagick

http://www.imagemagick.org/Usage/masking/#masks

I was wondering if there was some way to mimic the behavior (like cutting the image up based on a black image mask that turns image parts transparent... )

and then trim that image in game...

trying to hack around with the webcam feature and reproduce some of the imagemagick opencv stuff in it in Unity but I am saddly unequipped with masks, shaders etc in unity skill/knowledge.  Not even sure where to start.


texts: What is the game development market shifting towards?

texts: Aimed at the professionals who are there in the industry, what is the game development market shifting towards? Web-based or Mobile or Consoles/PCs. I have developed a decent knowledge of JavaScript and html5, so I want to know if this is entirely useful(on a game development perspective) or maybe I should learn some other language from scratch?


texts: Simple 2D Collision Detection Algorithm Library

texts:
I'm building a simple OpenGL game and I was looking for some simple collision detection library for objects like squares, triangles and circles. Any suggestions?

PS: Preferably a library that is very well documented and provide examples of 2D collision detections.


texts:
To followup from a previous query - I need some help with the implementation of easystorage high scores, which is bringing up some errors on the xbox.

I get the prompt screen, a savedevice is selected and a file are all created! However the file remains empty, (I've tried prepopulating but still get errors).

The full portions of the scoring code can be found here: http://pastebin.com/74v897Yt

The current issue in particular is in LoadHighScores() - "There is an error in XML document (0, 0)." under line data = (HighScoreData)serializer.Deserialize(stream);

I'm not sure whether this line is correct either: HighScoreData data = new HighScoreData();

public static HighScoreData LoadHighScores(string container, string filename)
        {
            HighScoreData data = new HighScoreData();

        if (Global.SaveDevice.FileExists(container, filename))
                {
                    Global.SaveDevice.Load(container, filename, stream =>
                            {
                                File.Open(Global.fileName_options, FileMode.OpenOrCreate,
                                         FileAccess.Read);
                                try
                            {
                                            // Read the data from the file
                                        XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                                        data = (HighScoreData)serializer.Deserialize(stream);
                            }
                              finally
                             {
                                    // Close the file

                                stream.Close();
                             //   stream.Dispose();

                             }

                            });

                }

        return (data);
    }

I call: PromptMe(); when the Start button is pressed at the beginning.

I call: if (Global.SaveDevice.IsReady){entries = LoadHighScores(HighScoresContainer, HighScoresFilename);} during the menu screen to try and display the highscore screen.

I call: SaveHighScore(); when game ends.

I've tried altering the struct code to a class but still no luck.
Any help greatly appreciated.


texts: Converting a hipoly model to a lowpoly model

texts: I have a model with more than 500.000 polygons and I want to speed up the drawing process in my game. So I decided to use a lowpoly model and normal mapping, but found no software to get a lowpoly model from my hipoly model. Does anyone have an idea how to do this?


texts:
I have a question about UDP. For context, I'm working on a real-time action game.

I've read quite a bit about the differences between UDP and TCP and I feel I understand them quite well, but there's one piece that has never felt correct, and that's reliability, and specifically acknowledgements. I understand that UDP offers no reliability by default (i.e. packets can be dropped or arrive out of order). When some reliability is required, the solution I've seen (which makes sense conceptually) is to use acknowledgements (i.e. the server sends a packet to the client, and when the client receives that message, it sends back an acknowledgement to the server).

What happens when the acknowledgement is dropped?

In the example above (one server sending a packet to one client), the server handles potential packet loss by re-sending packets every frame until acknowledgements are received for those packets. You could still run into issues of bandwidth or out-of-order messages, but purely from a packet-loss perspective, the server is covered.

However, if the client sends an acknowledgement that never arrives, the server would have no choice but to eventually stop sending that message, which could break the game if the information contained in that packet was required. You could take a similar approach to the server (i.e. keep sending acknowledgements until you receive an ack for the ack?), but that approach would have you looping back and forth forever (since you'd need an ack for the ack for the ack and so on).

I feel my basic logic is correct here, which leaves me with two options.

Send a single acknowledgment packet and hope for the best.
Send a handful of acknowledgment packets (maybe 3-4) and hope for the best, assuming that not all of them will be dropped.

Is there an answer to this problem? Am I fundamentally misunderstanding something? Is there some guarantee of using UDP I'm not aware of? I feel hesitant to move forward with too much networking code until I feel comfortable that my logic is sound.


texts: Checking for Weapon Collision in a 2D overhead RPG game

texts:
I'm starting development on a 2D overhead RPG game, and am wondering what the best approach for handling weapon collision and dealing damage to enemies is.

I'm currently using a basic Entity/Component structure for my game objects.  I have a CharacterEntity, that has an EquipableEntity data member.  The CharacterEntity has a component that listens for input.  When a command to attack is received, the CharacterEntity is set into an attack mode where an attacking component gets the equipped entity and moves it in the attacking motion.  Any collisions detected with the moving equipped entity in the world are then registered as successful attacks.  Once the attacking component determines the attack is finished, the CharacterEntity leaves attack mode and returns to it's normal state.

Weapon collision is a basic LWJGL Rectangle that tests the .interesects() method, checking against all enemy rectangles.  Currently it's just a stabbing motion (it moves out to x length, then returns).

The reason I did it this way was:

1) I wanted enemies to receive and respond damage as the sword crosses their path, instead of just saying "attack occurred in this general area" and having all enemies update at once.  In the stabbing case, an enemy at the full length of the sword wouldn't take damage until the actual sword entity crosses it's path.
2) The weapons define their own appearance and boundary on the screen, making it easier to animate and sync with the game.

I'm entirely new to game development (if you haven't figured that out already).  Is this the appropriate way to achieve the result I'm looking for, or complete overkill?  How does a game like Terraria (where weapons move in a sweeping motion) or the Zelda series handle attacking and determining what enemies to hit and when?  Am I on the right path or totally off?

Any advice or suggestions would be greatly appreciated.


texts: Decaying velocity for simple ball physics

texts:
I am writing a little experimental 2D program in Java to understand the basics of physics in games. I read this article on game physics to get me started and want to implement the simple Euler method (it is discouraged in the article, but this is just an experiment). My "Ball" class looks like this:

public class Ball {
    double x, xv, fx; //position, velocity, force
    int xdir = -1;
    double rad = 20;
    double mass = 1;

    public void tick(){
        x = x + (xv*xdir) * STEPTIME;
        xv = xv + (fx/mass) * STEPTIME;
        fx = 0;
    }
//STEPTIME is 0.02

For now, I want to focus on horizontal movement. In the end, I want to be able to drag the mouse in the window and have a bawn spall with force applied to it depending on the distance of the drag.
The tick() function implements the following equations (from the article):

acceleration = force divided by mass
change in velocity = acceleration * delta time
change in position = velocity * delta time

My problem is, that I do not know how to decrease the velocity again. When force is applied in a single frame, velocity will then ben constant. If force is applied continuously, velocity will become infinite.
Since the ball is supposed to return to an idle state after it force has been applied to it in a single frame, the velocity has to decay over time.
If I apply a constant negative velocity (to simulate drag), then velocity will soon be negative and the ball will move in the opposite direction.

What is a good way / best practice to decay the velocity of an object over time ?


texts: How can I make the camera to rotate from side side but in static movement range?

texts:
I mean for some reason now the camera is rotating to the left and to the right but sometimes it's rotating to one of the sides a lot I mean a very sharp angle and sometimes less rotation.

How can I control how much rotation will be from side to side by degrees ?

using UnityEngine;
using System.Collections;

public class scr_camera : MonoBehaviour {

    public float rotate_amount;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        transform.rotation = Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) * rotate_amount) + transform.eulerAngles.y, transform.eulerAngles.z);
    }
}

Sometimes cam14 make almost 240 even close to 300 degrees rotation to one of the sides sometimes less. The rotation is not equal to both sides. I want simple rotation to both side just to see the room and not the walls behind the camera.

In this case I set the rotate_amount to 7 so it will rotate faster.


texts:
I'm trying to build a mod that places zones on a keypress. How would I accomplish this?
So far I've detected the keypress. But when I modify m_blocks in ZoneManager by calling block.setZone(x,y,zone) The block appears to have changed, but only for the moment. When I run the keycommand again, the data appears to have  been reset. I never see the zone change in game, only when I print it to the console.
string outtext = "";
            uint blockCount = Singleton<ZoneManager>.instance.m_blocks.m_size;
            outtext += "start{\n";
            for (int index = 0; index < blockCount; index++) {
                var block = Singleton<ZoneManager>.instance.m_blocks.m_buffer[index];
                if (block.m_valid != 0) {
                    block.SetZone(1, 1, ItemClass.Zone.Industrial);
                    block.RefreshZoning(0);
                    outtext += " valid:" + block.m_valid + " position:" + block.m_position.ToString() + " zone:" + block.GetZone(1, 1) + " \n ";
                }
            }
            outtext += "}";
            Debug.Log("OUTTEXT " + outtext);

I've tried calling block.refreshZoning() as well, but I'm not sure how to calculate the blockid :(.


texts: AS3/Flashdevelop - Controlling a 2D character to move around a planet with gravity

texts:
With a little help I have managed to create a 2D planet with working gravity that constantly pulls a character towards its center. The only problem now is that I am completely stumped on how to make it so the user is able to make this character traverse the planet as one would expect rather than the simple up/down/left/right we are used to in natural platformers.

It should be noted the planet being traversed will have platforms/layers to jump and fall onto, so the moving and jumping should be in relation to the center of the planet, where the center of the planet acts as "down" would in a traditional platformer (which is why I seem to think I need a complicated way to create this kind of natural movement).

I had the idea of recalculating a new left and right direction to move in every time position is changed but the logic I have to work out to achieve this is beyond my knowledge.

Is this the only way to go or should I try tackling the problem differently? I hope not because I don't think I'd be able to achieve this otherwise.

This is my current code showing how the gravity works, with a simple placeholder for movement that just allows the character to move up/down/left/right on the screen:

public function moveChar(event:Event):void
    {
            if (leftPressed)
            {
                character.x -= mainSpeed;
            }
            if (rightPressed)
            {
                character.x += mainSpeed;
            }
            if (upPressed)
            {
                character.y -= mainSpeed;
            }
            if (downPressed)
            {
                character.y += mainSpeed;
            }
        }

public function gravity():void
{
    //tan2(planet.y - player.y, planet.x - player.x)
    angle = Math.atan2((planet1.y + 2245) - (character.y+5), (planet1.x+2245) - (character.x+5));
    gravityX = Math.cos(angle) * gravitationalAcceleration;
    gravityY = Math.sin(angle) * gravitationalAcceleration;

    //distance = Math2.Pythagoras(planet1.x + 50, planet1.y + 50, character1.x + 5, character1.y + 5);
    distance = Math.sqrt((yDistance * yDistance) + (xDistance * xDistance));

    //Calculate the distance between the character and the planet in terms of x and y coordinate
    xDistance = (character.x + 5) - (planet1.x + 2245);//320 to 50
    yDistance = (character.y + 5) - (planet1.y + 2245);//320 to 50

    //Make sure this distance is a positive value
    if (xDistance < 0) {
        xDistance = -xDistance;
    }
    if (yDistance < 0) {
        yDistance = -yDistance;
    }

    //Update the current velocity before new velocity is calculated
    initialXVelocity = finalXVelocity;
    initialYVelocity = finalYVelocity;

    //Send the character into the correct direction
    character.x += gravityX;
    character.y += gravityY;

    //Basic collision detection of the surface, basic stop of gravity
    if (distance <= planet1Radius) {
    trace("hit!");

    if (planet1.x - 2180 < character.x - 5) { //320 to 50
        character.x -= gravityX*1.025;
    }
    else {
        character.x += gravityX*1.025;
    }
    if (planet1.y - 2180 < character.y - 5) { //320 to 50
        character.y -= gravityY*1.025;
    }
    else {
        character.y += gravityY*1.025;
    }
    } else {
    trace(" no hit!");
    }
}

edit1:
I now have this code thanks to @DMGregory:

var characterPosition:Point = new Point();
var planetPosition:Point = new Point();
characterPosition.x = character.x;
characterPosition.y = character.y;
planetPosition.x = planet1.x;
planetPosition.y = planet1.y;

var localUp = normalize(characterPosition - planetPosition);
var localRight = new vector2( -localUp.y, localUp.x);

However, I have trouble understanding the syntax I should be using here, and also for when I need to move the character. Should it look something like this:

if (rightPressed)
{
    character.x += localRight;
{
if (leftPressed)
{
    character.x -= localLeft;
{


texts:
How can I spread my texture evenly across a cylinder in Unreal Engine 4?

Specifically, in the image below, I would like have texture on cylinder (on the left) match the one on the box (on the right). I need a many sides because I want the cylinder to be very smooth.


texts: Does XNA's content pipeline alter my FBX files?

texts:
Basically I'm trying to export a model in fbx format through the XNA content processor and I'm finding that the model itself is getting modified and being shifted slightly to the right and being scaled down a bit too. I am certain the FBX file being exported by 3D Studio Max is properly alligned at the center and of a larger scale.

If I export an FBX file with more than one mesh in it the exporter seems to work fine, so not sure what's up with that either...

*Just found that no matter what rotation/orientation I give a model XNAs content exporter seems to reset it to an identity matrix. i.e. I create a long box and give it an angle of 20degrees, XNA resets it to 0 degrees when I draw it...

THis is as it appears in 3D StudioMax: http://i.stack.imgur.com/e0oW4.png

This is how it appears in XNA: http://i.stack.imgur.com/1vOcx.png

Both are being viewed from the same angle and direction but varying distances.

Now what is really odd is if I create another mesh in max, say a box, and export that (along with the original model), it works fine: http://i.stack.imgur.com/SIDg9.png

So long as there is more than one mesh in the fbx model it draws fine, if there is less its orientation which I applied to it in 3D studio max is removed when I draw it.

Here's my code for drwaing the mesh:

model.CopyAbsoluteBoneTransformsTo(boneTransforms);
foreach (ModelMesh mesh in model.Meshes) {
    foreach (BasicEffect effect in mesh.Effects) {
        effect.World = boneTransforms[mesh.ParentBone.Index];
        Vector3 cameraPosition = Camera.Get.Position; // new Vector3(0, 0, 0);
        //cameraPosition.X = -Camera.Get.PosX;
        //cameraPosition.Y = Camera.Get.PosY;
        effect.View = Camera.Get.View;
        // Matrix.CreateLookAt(cameraPosition, cameraPosition + Camera.Get.LookDir,
Camera.Get.Up);

        effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4
            , BaseGame.Get.GraphicsDevice.Viewport.AspectRatio
            , 0.01f, 1000000);
        //Matrix.CreateOrthographic(800 / 1, 480 / 1, 0, 1000000);

        //effect.TextureEnabled = true;
        effect.LightingEnabled = true;
        effect.PreferPerPixelLighting = true;
        //effect.SpecularColor = new Vector3(1, 0, 0);
    }

    mesh.Draw();
}


texts: Is there a significant amount of overhead when using STL containers instead of plain arrays?

texts: I have read discouraging statements about using plain arrays in c++. Where videogame development is involved we are aiming, as far as I know, at max speed execution. STL containers (such as std::vector) bring some elements not present in plain old arrays (iterators, etc). Does such functionality add overhead? (e.g. pointer chasing, etc) If so, is it worth it in real life to lose some speed in exchange for type safety?


texts:
I'm using OpenGL (with LWJGL) in Java, but the question is language independent.

I have some region (a rectangle for simplicity), and, let's say, a big tiled map which I want to show in this area. The area is not the whole screen, I want to render something around it.

I can think of two approaches, but they are not very good and hard to do.

Render the whole tiled map and everything else, including background and the frame,
on top - leaving the window. Yes, works, but it'd be pain.
Render only visible tiles and only the visible portions of the border tiles.
This is not possible if I for example render a font using external library - there I don't have such fine control.
Some OpenGL trick?

Please, guide me.


texts: How to un-publish a game with minimum impact?

texts:
I released a game about 5 years ago across multiple mobile platforms. I spent a couple of years supporting it, following user feedback and trying to improve its revenue unsuccessfully. In the end, I just patched all the holes I could and left it be.

Recently, I started getting a bunch of support requests for android. I don't know if it's an OS update clashing, or what, but I'm unable to do anything about it. I switched version control and backups a while (2 years or so) ago, and the earliest version of the code I have access to is from part way into a major overhaul and work on a sequel that I decided wasn't sustainable. In order to issue fixes I would need to finish the overhaul and there's no way I can afford to do that.

So... what is the best way to handle this? I was thinking of issuing refunds to the people with support requests and un-publishing from the store fronts. However, I don't want people who've just bought it to see it suddenly vanish. That's only an issue for Google Play (I don't really get any sales anywhere else now). I'm not sure if making the game unlisted would still allow players to access it from the "My Apps & Games" section in Google Play, or if any would realise if they could. Is there a better way?

Cheers


texts:
My game is a 2D, top-down game where you aim with the mouse and the gun follows it. I'm trying to get the bullet to go in the direction of where the mouse is. The code will be a component of the bullet prefab.
here my code:

public class BulletBehavior : MonoBehaviour {

public float speed;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y);
}

private void OnTriggerEnter2D(Collider2D collision)
{
    Destroy(gameObject);
}

}


texts: Projectile initial motion to hit a target position

texts:
I'm working on a 3D game where i need to shoot a projectile (arrow) in order to hit a target position. The projectile has an origin position and a motion vector v(t) where "t" is a time unit. v(t) represents both the direction and force/speed (vector lenght). At every time unit friction and gravity are applied to the motion and the projectile position is changed to the previous one + current motion . So, overtime the motion changes and so does the projectile position creating a kind of ballistic motion. The problem is: given the projectile origin and target position, what's the initial motion?

You can find all the equations, formulas

As you can see I'm already able to get the initial motion using a constant t but that makes the projectile slow or fast depending on the distance between target and origin because it will always take the same time independently from the distance. I'm bascally not able to choose the initial motion vector lenght (which is the arrow speed), it depends on the constant t used. So what i need is to calculate a t depending on the speed i need.

I'm thinking about getting the t from the motion vector lenght = speed equation but it's too big, and i don't even know if it's the right/best way


texts: Unity3D URP - How do I approach creating Fog of War for 3D top-down stealth game?

texts:
What I try to achieve is a fog of war system for 3d top-down stealth game. I have searched the Internet and it seems that behavior I want to achieve can be done by using secondary camera that is rendering its output to a render texture. Then render texture is applied to a plane which sits above a map with a masking shader. I was following this video: https://www.youtube.com/watch?v=PNAvNeOTnSE however my project is using URP in Unity and the Clear Flags on camera settings is missing. So basically after each rendering loop render texture gets cleared and drawn again which makes impossible to "save" areas that already have been revealed by the player.
Maybe this can be done using another technique? I would like to have fog of war that covers entire rooms with black opaque plane and reveals them upon entering them but remains cleared once visited. However visited areas should be gray once left and enemies should be hidden from the player when not in line of sight. Something like in this video: https://youtu.be/jrK_Uvwwk9I?t=1247
I would really appreciate if someone pointed my in right direction.


texts: Game State query -- Are Game states and Game Phases the same thing?

texts:
I am currently writing a simple board game app.

I have written some basic states which are more to do with global state of the game.

Currently they are just enums, they don't really do anything nor is there a manager.

Something like this;

enum {
GameStateInitialize = 0,
GameStatePlaying = 1,
GameStatePaused = 2,
GameStateEndGameConditionMet = 4
}

Most board games I've played have a linear list of "phases", my own digital board game tries to replicate this. During the GameStatePlaying the board game has various phases, sequentially driven; again these are just enums for now.

enum {
PhaseBuying,
PhaseProduction,
PhaseSelling,
PhaseTaxes,
PhaseUpdateDemand,
PhaseUpdatePlayerTurnOrder
}

During PhaseTaxes it will check for whether a game end condition has occurred; if it has it needs to trigger the GameStateGameEndConditionMet

Here's the problem I'm having.

Could game-phases, and game-states be combined?  I'm really not sure how to make sure that it doesn't do a certain phase if the game end condition has been met?

Should gamePhase and gameState the same?

Thanks


texts: When should I clear an auxilliary render target?

texts:
I'm using a few different render targets in my game in addition to the back buffer. These other render targets are only used in a few places, for specific tasks.

I'm wondering when I should be clearing them. Right now I clear all of my render targets at the beginning of the frame, and it seems like I'm waiting for all the textures to clear before the rest of the drawing gets underway.

Would it be more efficient to clear these textures later in the frame, when they aren't being used? Is there any hope of the GPU sort of clearing them "on the side" while unrelated rendering is happening? Or are these tasks always sequential and will I always need to wait for clearing?


texts: I'm trying to draw a 2D plane that has minimum dimensions to contain a 3D model (a sphere). How do I calculate the minimum size and position of the rectangle to completely cover a 3D model on screen?


texts: Divide rectangular image into fixed number of random sized rectangles + 1 fixed size rectangle

texts:
I'm trying to divide a rectangular image into a fixed number of smaller rectangular image parts (of random but bounded width / height), with the exception of 1 rectangle which is predefined in position and size.

So, for example:

My first thought was:

Generate list of possible points
From this list remove all points in the fixed size rect
From this list remove all points that can't possibly meet the other requirements (e.g. points close to the image edges that wouldn't meet the required bounded min / max rect size)
Then randomly pick a point, generate a random bounded width / height, see if this intersects any current rect, until we find one that doesn't
Record rect, remove all points in rect from list
Repeat

However this seems slow, overly-complex and still results in holes because sometimes there's no more room for the minimum size of rect to fill the last bit of space.

I've looked into algorithms involving squaring the square, packing routines and such like, but nothing I've found helps with the additional constraint that one rectangle is predefined and the rest can be random.

Not looking necessarily for a full algorithm, but hints at an approach would be appreciated.


texts: In Unreal, what are the differences between C++'s float and FFloat32?

texts:
I have been trying to learn some deeper aspects of UE4 and while reading many examples codes and also the source base of the engine, I noticed that sometimes people (and the very source code) use the standard C++ float primitive, but sometimes use UE4's custom implementation FFloat32.

Then I got curious: when programming a game with Unreal, what are the differences between using those 2 options and possibly what are the main cases when one should drop the standard C++ primitive in favor of the engine's implementation?


texts: 3d Dynamic liquid wobble inside a container in Unity3d

texts: How can I implement dynamic liquid wobble inside a bottle in Unity3D as seen in here? (Yellow liquid inside the spray can at 3:10)


texts: LIBGDX font.draw() makes letters blink on PC

texts:
I load Bitmapfont then try to draw it, but on PC(desktop) build screen blinks with frequecy that I can judge that backbuffer is not drawn. On Android all is fine, I don't see blinking. I simply do this:

SpriteBatch = new SpriteBatch();
Bitmapfont font = new Bitmapfont();
font.setColor(Color.GREEN);
spriteBatch.begin();
font.draw(spriteBatch, "Hello world", 0, 100);
spriteBatch.end();

Ways to fix?


texts: Object activate it self without script order?

texts:
I have strange thing here in my script. In this script clock_time turn active lamp object one by one. Where Lamp object turn off after 3 seconds be anther script. If clock time reach 120 or higher again lamp turn active !! Also, light_timer keep counting if lamp is active ??

 public GameObject[] lights; // 3 lamps
public int number;
public int[] light_timer; // 3 values "2,4,6"
public int clock_timer;

void Start()
{
    // all gameObject "lamps" is off
    number = lights.Length -1;

}
void Update()
{
    if (gameObject.activeInHierarchy == true)
    {
        clock_timer = (int)Time.time;
    }
    else
    {
        clock_timer = 0;
    }
    for (int i = 0; i < lights.Length; i++)
    {

        if (clock_timer >= light_timer[i] && lights[i].activeInHierarchy == false)
        {
            lights[i].SetActive(true);
        }

        if (lights[i].activeInHierarchy == true)
        {
            light_timer[i] = light_timer[i] + 1;
            print("me : " + i);
        }

    }

}


texts:
hello i have a error "object reference not set to an instance of an object"

when my ball collide with the spikes.its supose to remove one heart but it doesnt.

health code:

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

public class Health : MonoBehaviour {
  public int health;
  public int numOfHearts;

  public Image[] hearts;
  public Sprite fullHeart;

  // Use this for initialization
  void Start () {

  }

  // Update is called once per frame
  void Update () {
    if (health > numOfHearts)
    {
      health = numOfHearts;
    }

    for (int i = 0; i < hearts.Length; i++)
    {
      if (i < health)
      {
        hearts[i].sprite = fullHeart;
      }
      if (i < numOfHearts)
      {
        hearts[i].enabled = true;
      }
      else
      {
        hearts[i].enabled = false;
      }
    }

  }
  public void Damage(int dmg)
  {
    numOfHearts -= dmg;
  }
}

spikes code:

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

public class Spikes : MonoBehaviour {

  private Health Player;

  // Use this for initialization
  void Start () {
    Player = GameObject.FindGameObjectWithTag("Player").GetComponent<Health>();

  }

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

  }

  void OnTriggerEnter2D(Collider2D col)
  {
    if (col.CompareTag("Player"))
    {
      Player.Damage(1); // here i have the error.
    }
  }
}


texts:
First off, excuse my ignorance. I am just getting started in game dev. and ran into a little issue. So I had these weird rippling-lines going across my screen, and saw in a couple forums that this means I don't have what is called a "pixel perfect" game. To fix this, I am supposed to change the pixels-per-unit of each sprite down to 1. Currently I had it on 32 because that is my sprite size and I am a complete noob.
Now, I change it down to one but it completely destroyed my game. Everything that is generated on my map/grid is sucked into the center in this giant orb of sprites (I procedurally generate my map off a grid of 1/0s). I am guessing there is just a setting or some such thing that I am missing. Any ideas?
Also would be happy with an alternative to remove the rippling lines.


texts: Working out velocity/time based on physical pixels moved

texts:
In my game I integrate like so: (Please assume all variables to be declared)

sprite.xTimeInSeconds = 5.0; //Time in seconds it should take this object to cross screen
sprite.xVelocity = 1f/xTimeInSeconds;

And then I move it like so:

sprite.gridX+=sprite.xVelocity*dt;
sprite.x=sprite.gridX*screenWidth;

Then I simply render the sprite at those coordinates:

sprite.draw();  //Uses sprite's internal 'x' which was set above

So, everything within the game itself works fine - ie. all movement is correctly scaled regardless of device, but now I'm trying to write my own swipe/fling touch control system for a menu.

The menu does work - the user can place finger on screen, move up and down and when they release their finger, the menu keeps scrolling(* see below).  If they then press their finger down again, the scrolling stops immediately, as one would expect.

The only thing I'm having problems with is how to 'decelerate' the scrolling when the user releases their finger.  At the moment, it keeps scrolling at the same speed until it reaches it's limits or the user taps the screen to stop it.

Within my touch-scroll method, I'm simply detemining how much the users finger has moved by and then moving my objects by the same amount.  What I need to know (and can't figure out), is how can I - from knowing only the amount of pixels moved, work out the 'time' variable above?  (once I have this I can then decelerate at a scaled amount on all devices).


texts: Is there algorithm for boxcasting or thickray casting?

texts:
I am not sure what the correct name is called but here is my problem: I have implemented a casting ray function that works as expected. However, because I am using a loose grid structure, (ie, objects that overlap multiple grids are only put into one grid), the ray cast may miss certain objects. What I need, I think is a box casting where I need to get every grid the box hits from its initial position to final position. Does anyone have such algorithm? Or pointing out to a solution to this problem, thanks!

This pic from N tutorials is a nice summary of this problem:

My ray cast implementation only hit the blue cells but as you can see, it may miss certain objects. They are only put into the grid where the x is.

Just to add I will be using this in a heated loop and so I have the additional requirement that this must be done efficiently.

EDIT: this picture illustrates why I think a box casting would work for loose grid: (The box must be bigger than the objects contained in the grid.)


texts: How can I get my first-person character in Unity to move to a ledge with an animation?

texts:
I'm trying to get this to happen:
The character walks up to a large crate, the player presses a button, and an animation starts playing where the character climbs up on to the crate. (all in first person view).

So far I tried this with normal "First Person Controller" Prefab in Unity.

My code so far:

function OnTriggerStay(other : Collider){
    if(other.tag == "GrabZone"){
        if(Input.GetKeyDown("e")){
            animation.Play("JumpToLedge");
        }
    }
}

However when i use this on The FPC it will always play from the position the animation is created on.

I also tried to create an empty game object, placing the FPC in there. Gives same effect.

I also tried just animating the graphics of the FPC alone. This seems to work but since the Character Controller itself is not animated that stays onthe ground. So the whole FPC wont work anymore.

Is there anyway i could let this animation play on the local position the player is on at that time?

Or can you think of any other logical solution for a grab and climb?


texts: THREE.JS - How to know the shortest rotation direction an object must do to look at other?

texts:
I am trying to understand a way in THREE.JS (and the mathematical foundation) to get the direction an object should rotate to lookAt other but without actually rotate it.
I've tried to use lookAt but that rotates the object completely.

I want to apply a small custom parameterized rotation on that direction.
So I don't want all the rotation, just the direction of that shortest to look at rotation.

So, basically I have 2 object positions and I want the shortest rotation direction of one of them so that one looks at the second object position, independently of the second object rotation.
And limit the axis so it works on a over the top 2d game setting (although the graphics are 3d)..

The rotation must be around Z for example.

And relative to the current object heading as this will be computed on each game loop iteration depending on the player position.

This is intended for a game where enemies try to follow the player but turn slow to look at him.

Thank you in advance


texts: "Unable to create OpenGL 3.3 context (flags 0, profile 1)"

texts:
Trying to run any of the well-known McKesson's tutorials on a friend's laptop results in the aforementioned exception.

I read that in order to run applications which use OpenGL 3.3 you must at least have an ATI HD or Nvidia 8xxx GPU series. He has an ATI HD class graphics processor which eliminates (maybe) this issue. Also, I read that this error may result in having old drivers. He updated his drivers but that didn't solve the problem.

The tutorials are built as said in the book introduction and glsdk is installed.

If more information is needed, say so and I will provide it.

What are the other reasons for this kind of exception? And how can I fix them?


texts: Is there a way to make GUI.SelectionGrid expand horizontally

texts: I am working on an inventory system, And I want to be able to make a Selection Gird that expands horizontally rather than vertically, is there an easy way to do this? Or will I have to create my own version of SelectionGrid?


texts: Compile-time checking for component-based, data-driven games

texts:
This is not a specific question, but rather someone who is looking for opinions about a typical design problem. In a component based data-driven games, I've often seen something similar to the following when accessing attributes:

int* health = mOwner->get< int >( HEALTH_ATTRIBUTE );

if (health)
    *health -= 10;

Or, alternatively:

if (mOwner->hasAttribute( HEALTH_ATTRIBUTE ))
{
    int health = mOwner->get< int >( HEALTH_ATTRIBUTE );
    mOwner->set( HEALTH_ATTRIBUTE, health - 10 );
}

Where mOwner is a pointer to the parent game object. In this example, assume that the game object stores a map of attributes which are downcasted to the correct type at runtime.

There are some problems with this approach. Mainly, it is prone to bugs since it requires the programmer to know the the type of the attribute they are after. If I was working on a small team or by myself, this wouldn't be an issue. However for my requirements, this is undesired.

The only way to have compile-time checks is to create a helper function for each attribute that returns the proper type, so our code would then look like:

int* health = Attributes::getHealth( mOwner );

Where Attributes is declared as a namespace. Because the type is known at compile time, this gives us several advantages. In addition to the compile-time check, we gain the flexibility to easily declare certain attributes as constant, or that can't be modified outside the game object, etc. Of course, the downside is that it becomes necessary to manually create a new function for each and every attribute in the game.

Thoughts? Opinions?

EDIT:

After thinking it through a little more, I realized there is a way to define the function once using templates to avoid code duplication. For example:

template <typename Type, int ID>
class Attribute
{
public:
    typedef Type type;

    static int getID()
    {
        return ID;
    }

    static type getData( const GameObject* obj )
    {
        return obj->getAttribute < type >( ID );
    }

};

And then for each attribute we have in our game,

typedef Attribute< std::string, MODEL_NAME > ModelName;
typedef Attribute< Vector3, POSITION > Position;
typedef Attribute< int, HEALTH > Health;

/// ... and so on ...

And when we want to access an attribute:

int health = Health::getData( mOwner );

Or alternatively, if we want to:

Health::type health = Health::getData( mOwner );

If we don't know the health attribute exists or not:

int* health = Health::getData( mOwner );

if (health)
   // ....

I think this approach gives a lot of flexibility while still maintaining type safety.


texts: Profiling code with threads and script interpreter

texts:
Basically, how I profile a game that have multithreading and script interpreter? (Lua in my case)

I have no idea of where to look for that.

Also it would be nice to be able to profile code that resemble somehow the release code, my "debug" binary is about 12 times bigger...

EDIT: My game was made with C++, compiled with GCC, runs on Windows and GNU/Linux for now, compiled natively (ie: MingW on Windows, regular GCC on GNU).


texts: Why does my 3d model become invisible as I move the camera away?

texts:
I'm trying to load a 3d model from Mixamo:

//        let scene = SCNScene(named: "art.scnassets/ship.scn")!
        let scene = SCNScene(named: "art.scnassets/Ch45_nonPBR.dae")!

    // create and add a camera to the scene
    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    scene.rootNode.addChildNode(cameraNode)
    scene.fogStartDistance = 10000
    // place the camera
    cameraNode.position = SCNVector3(x: 0, y: 40, z: 100)

    // create and add a light to the scene
    let lightNode = SCNNode()
    lightNode.light = SCNLight()
    lightNode.light!.type = .omni
    lightNode.position = SCNVector3(x: 0, y: 50, z: 10)
    scene.rootNode.addChildNode(lightNode)
    lightNode.light?.intensity = 10000;

    // create and add an ambient light to the scene
    let ambientLightNode = SCNNode()
    ambientLightNode.light = SCNLight()
    ambientLightNode.light!.type = .ambient
    ambientLightNode.light!.color = UIColor.white
    scene.rootNode.addChildNode(ambientLightNode)

    // retrieve the ship node

//        let ship = scene.rootNode.childNode(withName: "ship", recursively: true)!
        let ship = scene.rootNode

While the z value for the cameraNode position is 100 or less, I can see the 3d model. But if I increase the value, then the model is no longer visible. Even at 100, parts of the model are not visible.

Is this a problem with lighting or rendering distance ? I would like to move the camera far away so that I can see the whole model on screen. Right now I can only see a part of it.  What do I need to change so I can see the whole model clearly like this:

EDIT: I am using Swift 5


texts: Fragment shader - map dot texture repeatedly over the sphere

texts:
I have a sphere and in Fragment shader, I have available lat / lon position (in radians) for every fragment. I have a texture of a single dot. I need to map this single dot (or any other texture) repeatedly over the sphere and create a pattern like a "golf ball" (for example this sample: https://www.shadertoy.com/view/Xs2fWy - however the dots are calculated directly from raytracing plus the code is not commented, so not very clear). I donw want to pregenerate texture, because I want to dynamicly change the number of dots.
Is there a solution how to achieve this only in fragment shader? I cannot modify anything else.


texts: How to calculate/detect the force of a collision? (Game-Maker Studio)

texts:
How can I use game-maker to detect the force in a collision between two mobile (not fixed) objects?

This is used for damage calculation and possibly compression calculation.

My problem is this: while net force can be calculated using mass and acceleration, the idea of damage is focused on the individual components of the force applied on an object. For instance, if a car is pushing another car against a wall, even though there are no acceleration, people will logically feel like some damage must be done to both cars because forces were conferred on them. I want to know if there is some underlying mechanism in game maker's physics system (I use the latest version) that actually calculate a reaction force from the wall on the car so I can use it to calculate damage.


texts: How would one go about integrated python into a c++ written game for the use of user-made scripts

texts:
I'm quite new to game development  (not the site) and I'm currently just trying to educate myself about some certain things before I really begin working and a game.

anyway, I'd like to know what basic algorithm/outline of how a game would be coded effeciently with the implementation of user coded scripts for gameplay and levels that are written in python,

Is this even possible? would all the features of python be avalible? like say "multi-threading"?


texts: Using Ogre particle point billboards with shaders

texts:
I'm learning about using Ogre particles and had some questions about how the point type particles work.

Q. I believe point type particles are implemented as a single position. Is one single vertex is passed to the vertex shader?

Q. If one vertex is passed to the vertex shader then what gets sent to the fragment shader?

Q. Can I pass the particle size to the shader? Perhaps with a custom parameter?


texts: XNA/MonoGame/SharpDX: Pixel shader with sprite sheet

texts:
I've searched around for two days now on the internet but cannot find a solution. I've also read up on Pixel Shaders on MSDN with no luck.

I'm trying to apply a simple pixel shader to a sprite batch for alpha masking. It worked fine when I used two separate textures; one for the sprite and a matching one for the shader.

Problem is I don't want to do this. I'd like to use my sprite sheet and source rectangle and use a separate mask from a sprite sheet of masks.

However it doesn't work. The sprite draw perfectly but the mask does not and appears to be using a sprite at a different locating in the mask sheet. It has something to do with getting the coordinates of the mask.

My idea was if the sprite to draw was at 200*200 in the sheet, subtract the correct tex coordinates from it to get the pixel, then add this to the mask.

pos = texCoord - sprite start = offset + mask start = location of mask from current pixel

EG;
pos = 200*200 - 200*200 = 0 + maskPos = 440*330
pos = 201*201 - 200*200 = 1 + maskPos = 441*330

UPDATE: It is definitely converting the coordinates of the sprite to the mask that is the issue. I've tried numerous methods to try and convert this and normalize the coordinates to singles with no luck.

The result after masking
The mask being applied
The actual mask that should be applied

I have no idea why the result is being botched and section cut out like shown in image one.
22 is the width and height of both masks and sprites. 512 is the width and height of both sprite sheets.

To calculate the pos in the mask that generate the botch:

float maskPixelX = (inCoord.x * 512) + X pos to draw the tile;
float maskPixelY = (inCoord.y * 512) + X pos to draw the tile;
float2 maskCoord = float2((maskPixelX - maskpos.x) / 22, (maskPixelY - maskpos.y) / 22);

Pixel shader:

uniform extern texture ScreenTexture;
sampler screen = sampler_state
{

    Texture = <ScreenTexture>;
};

uniform extern texture MaskTexture;
sampler mask = sampler_state
{
    Texture = <MaskTexture>;
};

float2 startpos;
float2 maskpos;

float4 PixelShaderFunction(float2 inCoord: TEXCOORD0) : COLOR
{

    // Get the matching pixel offset in mask.
    float2 pos = inCoord - startpos;
    pos = pos + maskpos;

    float4 color = tex2D(screen, inCoord);
    float4 color2 = tex2D(mask, pos);
    if (color2.a > 0) color.rgba = 0;
    return color;
}

technique
{
    pass P0
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

And here is the draw call:

  mask.Parameters("MaskTexture").SetValue(maskSheet) ' Sprite sheet with mask.
  mask.Parameters("startpos").SetValue(New Vector2(200, 200))
  mask.Parameters("maskpos").SetValue(New Vector2(440, 330)) ' Postion of mask in sheet.
  Dim source As New Rectangle(200, 300, 22, 22)
  spriteBatch.Draw(sprites, Vector2.Zero, source, Color.White, 0.0F, New Vector2(0, 0), 1.0F, SpriteEffects.None, 1.0F)


texts: How can i detect if the player is inside an explosion radius?

texts:
I'm making a driving game, there are enemies which spawn on the side of road and when my player car gets close, they fire a rocket in front of the player. I need to detect if the car is within a certain radius of the explosion center. So when I can detect that I'm assuming I can then use rb.AddExplosiveForce to make the car fly a bit or something.

What is the recommended way to get the blast radius collider (or equivalent) and detect if the player is inside it?


texts: Shadows go through meshes, and also being applied to itself

texts:
I am using Ogre3D and I am using stencil shadows for my character. They work pretty well, but I have 2 problems: first, the shadow is applied to the entity it is casting the shadow, and secondly, the shadow goes through all the entities on the screen, and I would like to apply the shadow to only the first entity.

Also, the shadow gets rendered on the back of the model.

Images showing the problems:


texts: Having a problem with referencing Farseer into my Monogame project

texts:
I am trying to load in the Farseer Physics Engine into my current Monogame project and whenever doing so, the Farseer solution will load in correctly but then when I try and reference it, it gives me an error:

I cannot find any information or anyone else that had this issue so if anyone has any tips or solutions on how to include or reference this project then I would appreciate it greatly.


texts:
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!");
sf::VertexArray Tquad(sf::Quads, 40*40*4);
int size{ 20 };
int width{ 40 };
for (int x = 0; x < width; x++)
{
    for (int y = 0; y < width; y++)
    {
        sf::Vertex* quad = &Tquad[(x + y * width) * 4];
        quad[0].position = sf::Vector2f(x, y);
        quad[1].position = sf::Vector2f((x+1)*size, y);
        quad[2].position = sf::Vector2f((x+1)*size, (y+1)*size);
        quad[3].position = sf::Vector2f(x, (y+1)*size);
    }
}

while (window.isOpen())
{
    sf::Event event;

    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }

    window.clear();
    window.draw(Tquad);
    window.display();
}

return 0;

}

Hello , im getting very low fps with only 40x40 tiles, in release mode i get 21 fps. If i disable the window.draw i get 2000+- fps.


texts: Game mechanic player following path looks very roughly

texts:
I want my player entity to follow a path, which works, but it looks very roughly. Like it would stuck everytime.

    bool arrivedX = false;
    bool arrivedY = false;

    float speed = 0.06f;

    if(bestway.empty()) {
        //arrived
    } else {

        if(entity->x < bestway.front()->x * gridSize) {
            entity->x += speed * machine->getDeltaTime();
        } else if(entity->x > bestway.front()->x * gridSize) {
            entity->x -= speed * machine->getDeltaTime();
        } else {
            arrivedX = true;
        }

        if(entity->y < bestway.front()->y * gridSize) {
            entity->y += speed * machine->getDeltaTime();
        } else if(entity->y > bestway.front()->y * gridSize) {
            entity->y -= speed * machine->getDeltaTime();
        } else {
            arrivedY = true;
        }

        if(arrivedX && arrivedY) {
            bestway.pop_front();
        }
    }

the vector contains grid coords from 0 to WIDTH or HEIGHT / gridSize. And the entity has pixels coords. I have tried already:

entity->x / gridSize < bestway.front()->x

which runs smoothly, but when it goes up or right it will omit one grid tile. I think it is because of when the player is at pixel 19 and the gridSize is 20 it would calculate 0 . 19/20 = 0... I tried to ceil and floor it, but it didn't work out.
Hope you guys can help me.

edit:

        int ix = int( x + 0.5f );
        int iy = int( y + 0.5f );

        if(ix < bestway.front()->x * gridSize) {
            x += speed * machine->getDeltaTime();
        } else if(ix > bestway.front()->x * gridSize) {
            x -= speed * machine->getDeltaTime();
        } else {
            arrivedX = true;
        }

Video

http://youtu.be/-DugHbMdODg


texts: How can I fix my velocity damping to work with any delta/frame time?

texts:
I am decreasing my velocity by 50% every second using a guide I found online. I am using the code here and it gives the right result but only for very small values for dt:

float dt, velocity, position;

dt = 0.002f;
velocity = 1.0f;
position = 0.0f;

for (float t = 0.0f; t <= 1.0f; t += dt) {
    position += velocity * dt;
    velocity = lerp(velocity, 0.0f, 1.0f - std::pow(0.5f, dt));
}

printf("dt = %f, p = %f, v = %f\n", dt, position, velocity);

dt = 0.09f;
velocity = 1.0f;
position = 0.0f;

for (float t = 0.0f; t <= 1.0f; t += dt) {
    position += velocity * dt;
    velocity = lerp(velocity, 0.0f, 1.0f - std::pow(0.5f, dt));
}

printf("dt = %f, p = %f, v = %f\n", dt, position, velocity);

return 0;

But I am getting roughly the right velocity BUT two different final positions back when I use two different delta times (not due to floating point issues):

dt = 0.002000, p = 0.722848, v = 0.499308
dt = 0.090000, p = 0.784219, v = 0.473029

How can I fix this difference inside of my update loop?

How do I account for the extra acceleration between timesteps?


texts:
Im trying to make make game which is intended to be played with the phone in landscape mode, and the player uses their thumbs to control the movement. The game controls look like this:

On the left there is a simple button to accelerate, and on the right a wheel to adjust the direction. Both work perfectly when used individually but they won't work both at the same time.

I would need to implement multitouch and accelerate/rotate depending on which side of the screen the finger is on, but I can't figure out how to do that detection.

Below is the onTouchEvent, how can i modify it to do what i want?

@Override
    public boolean onTouchEvent(MotionEvent event){

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (event.getX() < 300 && event.getY() > 250) {
                    btnPress = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                x = (int) event.getX(); //this is used by the direction wheel
                y = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
                btnPress = false;
                break;

        }
        return true;
    }


texts:
I have a game where a wall is destroyed. I would like to click a button to reload the wall back to its initial state. I have only managed to reload the scene, using Application.LoadLevel(Application.loadedLevel)), but it takes to long.

How do I reload an object back to its original state?


texts: Can I reset the `[DisallowMultipleComponent]` attribute in child classes in Unity somehow?

texts:
Can I reset the [DisallowMultipleComponent] attribute in child classes in Unity somehow?
I want to create my base class:
[DisallowMultipleComponent]
public class MyCompanyClass : Monobehaviour {}

I want all my component scripts to inherit from the MyCompanyClass. So, I will be able to add only one instance of my component script to a game object at a time. I need it for most of my classes. But for some classes I still want to preserve the ability to add a few class instances to a game object, while still inheriting from the MyCompanyClass (because I am going to put some custom behavior into it, which is going to be used by all my component scripts).
So, I was trying to search for something like [AllowMultipleComponent], but found nothing. Is there maybe another way to achieve what I want?


texts: How to add the iPhone X screen dimensions to the mix of different iPhone screen sizes

texts: Generally for Unity I design all my artwork in Illustrator. So I start off with 1440x1920 (for portrait games) and outline a red frame of 1080x1920. So everything that fits well within the 1080x1920 usually covers the family of iOS devices for me. Then I set the  Pixels Per Unit to 192 for all my images. This approach has really served me well. Now that the iPhone X is in the mix, how can I cater for it in a similar way?


texts: Can you save a png in XNA larger than the backbuffer width?

texts: I'm looking at using the 'savetopng' method of the texture2D class to draw out custom textures. My problem is that my viewport is quite small (the application runs in a window) and the textures will often times run off the screen up to the maximum texture size of 2048px. If I know the texture size ahead of time am I able to instead create an array larger than the visible screen area. Or will the fact that the pixels are outside the viewport mean that they are not being rendered and as a result won't have the correct values?


texts: How to Bind Multiple Shapes/Models to One Vertex Buffer?

texts:
If I have two Vertex Arrays, one for Square, and one for Triangle; what is the best way to bind them to the VertexBuffer?

What are the patterns used to write multiple vertices to the VertexBuffer?  Streams?  Vectors?  Is there an Add, (+) overload that can be used like .pSysMem += anotherMesh.GetVertices()?

Is this possible with objects that have different numbers of Vertices?
Is this possible with objects that have different buffer element descriptions, (one with float4 position data, and another with float3 and texcoords, etc)?

Currently, I am binding one Shape, (a triangle), to the subresource like this:

ModelRenderer::StaticBufferDescription.ByteWidth = bufferSize;
ModelRenderer::StaticBufferDescription.BindFlags = D3D11_BIND_VERTEX_BUFFER;

ModelRenderer::StaticSubResourceData.SysMemPitch = 0;
ModelRenderer::StaticSubResourceData.SysMemSlicePitch = 0;
ModelRenderer::StaticSubResourceData.pSysMem = model->GetVertices();

DeviceManager::Device->CreateBuffer(
    & ModelRenderer::StaticBufferDescription,
    & ModelRenderer::StaticSubResourceData,
    & ModelRenderer::StaticBuffer);


texts: How to import in Unity, and use , "external" animation like the ones you can download on Mixamo?

texts:
I've a 3d Character with some animations. Then, i've found some animations on Mixamo i would like to use with my 3d model.

Do I need to merge them ?

If not, what's the correct way to download them and use in my project ?

Thanks


texts:
Could you help me to reduce this code as much as possible?
public GameObject[] TextPage;

public void Skin0()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[0].SetActive(true);
}
public void Skin1()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[1].SetActive(true);
}
public void Skin2()
{
    foreach (GameObject go in TextPage)
    {
        go.SetActive(false);
    }
    TextPage[2].SetActive(true);
}


texts: I want to save the result screen of the rendering and then apply another shader on that result, the typical way is to read the screen using glReadPixels and then buffer that image to gpu and then apply my effect, so is there a way to bind the screen result to a texture id directory in gpu, instead of retrieving it back to CPU and then buffer it to GPU ?


texts: GLSL associating multiple uniform samplerBuffers

texts: At the moment I'm not sure how my VBO and TBO associate with a specific uniform samplerBuffer in my shader, I have not linked them using the location or the vbo/tbo together. It seems to still work though, but now that I am using multiple samplerBuffers, how do I establish to link between a specific TBO and the uniform. Do I need to use glUniformX?


texts:
I was trying to implement a simple pathfinding, but the outcome is less satisfactory than what I intended to achieve. The thing is units in games like Starcraft 2 move in all directions whereas units in my case only move in at most 8 directions (Warcraft 1 style) as these 8 directions direct to next available nodes (they move from a tile to next neighboring tile). What should I do in order to achieve the result as in Starcraft 2? Shrink the tile size?

On the picture you can see a horizontal line of rock tiles being obstacles, and the found path marked as green tiles. The red line is the path I want to achieve.


texts: How do you create a 2d world then view it in 3d?

texts:
I have been learning OpenGL for a while now and have a pretty good understanding so far.

What I would like to know is if I create a 2D game in Orthographic Projection, is it possible to switch to a perspective projection and view the scene without having to manually adjust the camera etc?

Thanks


texts: Model a chain with different elements in Unity 3D

texts:
I have to model, in unity 3D, a chain that is composed of various elements. some flexible, some rigid. The idea is to realize a human-chain where each person is linked to the other by their hands.

I've not tried to implement it yet as i've no idea on what could be a good way to do it.
In the game i've to manage a lot of chains of people... maybe also 100 chains composed of 11-15 people. The chain will be pretty simple and there won't be much interaction... Probabily some animation of the people one at time for each chain and some physic reaction (for example pushing a people in a chain should slightle flex the chain)

the very problem of this work is that in the chain each object is composed by flexible parts (arms) and rigid parts (the body) and that the connection should remain firm... just like when people handshake... hands are firm and are the wrists to move.

i can use C4D to model the meshes.

i know this number may cause performance problems, but it's also true i will use low-poly versions of human. (for the real it won't be human, but very simple toonish characters that have harms and legs).
So actually i'm trying to find a way to manage this in a way it can work, the performance will be a later problem that i can solve.

If there is not a fast 'best-practiced' solution and you have any link/guide/doc that could help me in finding a way to realize this is, it would be very appreciated anyway if you post it.

thanks


texts: Workflow to animate character rig with an already animated model

texts:
How should I go about animating character rigs (walking, running, ducking, ...) with already animated assets? Do I load the animated asset into the project file of my character rig or do I attach the animated asset to the rig in the engine?

I am using Blender for the models and Unity3D as the engine.


texts: XNA: Camera's Rotation and Translation matrices seem to interfere with each other

texts:
I've been following the guide here for how to create a custom 2D camera in XNA. It works great, I've implemented it before, but for some reason, the matrix math is throwing me off.

public sealed class Camera2D
{
    public Vector2 Origin { get; set; }
    public Vector2 Position { get; set; }
    public float Scale { get; set; }
    public float Rotation { get; set; }
}

It might be easier to just show you a picture of my problem: http://i.imgur.com/H1l6LEx.png

What  I want to do is allow the camera to pivot around any given point. Right now, I have the rotations mapped to my shoulder buttons on a gamepad, and if I press them, it should rotate around the point the camera is currently looking at. Then, I use the left stick to move the camera around. The problem is that after it's been rotated, pressing "up" results in it being used relative to the rotation, creating the image above.

I understand that matrices have to be applied in a certain order, and that I have to offset the thing to be rotated around the world origin and move it back, but it just won't work!

public Matrix GetTransformationMatrix()
    {
        Matrix mRotate = Matrix.Identity *
            Matrix.CreateTranslation(-Origin.X, -Origin.Y, 0.00f) *  // Move origin to world center
            Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation)) * // Apply rotation
            Matrix.CreateTranslation(+Origin.X, +Origin.Y, 0.00f);   // Undo the move operation

        Matrix mTranslate = Matrix.Identity *
            Matrix.CreateTranslation(-Position.X, Position.Y, 0.00f); // Apply the actual translation

        return mRotate * mTranslate;
    }

So to recap, it seems I can have it rotate around an arbitrary point and lose the ability to have "up" move the camera straight up, or I can rotate it around the world origin and have the camera move properly, but not both.


texts: All Pairs Shortest Paths in Weighted Undirected Graph

texts:
I'm currently working on path-finding for my game and need help with finding an efficient algorithm to calculating the all-pairs shortest paths in a weighted undirected graph (each vertex in the graph represents a way-point on my map, and each edge represents the distance between pairs of way-points).

I have considered using Floyd's Algorithm due to its simplicity and relative memory efficiency, but Floyd was designed for a directed graph, whereas my graph is undirected. This means that Floyd's algorithm is rather more expensive than required given that I know that the shortest path from vertex A to vertex B is always identical to the shortest path from B to A.

Can Floyd's algorithm be optimized to deal with this duplication? Or is there an alternative algorithm fast/space efficient algorithm that I could use to solve the same problem?


texts:
I am aware this question has been asked before, but unfortunately I am new to the language, so the complicated explanations I've found do not help me in the least.

I need a lighting engine for my game, and I've tried some procedural lighting systems. This method works the best:

if (light[xx - 1, yy] > light[xx, yy]) light[xx, yy] = light[xx - 1, yy] - lightPass;
if (light[xx, yy - 1] > light[xx, yy]) light[xx, yy] = light[xx, yy - 1] - lightPass;
if (light[xx + 1, yy] > light[xx, yy]) light[xx, yy] = light[xx + 1, yy] - lightPass;
if (light[xx, yy + 1] > light[xx, yy]) light[xx, yy] = light[xx, yy + 1] - lightPass;

(Subtracts adjacent values by 'lightPass' variable if they are more bright) (It's in a for() loop)

This is all fine and dandy except for:

The system favors whatever comes first in the for() loop

This is what the above code looks like applied to my game:

On the left side you can see some weirdness going on:

The loop goes top to down then to the right column:

This is how the for() loop goes:

Light provided from my mouse, should be a full light, but is only half:

If I could get some help on creating a new procedural or otherwise lighting system I would really appreciate it!


texts: Unity - blur on one camera effects the other as well

texts:
I'm trying to fake a DOF effect for Sprites by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like Blur and Sharp accordingly.

So I have these 2 cameras, and I use Unity's Blur (optimized) script to blur things, and I have this script on only one camera, the one that is responsible for the blurred render.

I have the cameras like:

Cam 1:

Clear flags: Don't clear (this is the main, sharp cam)
Culling mask: sharp layer
has no blur effect (or any other post proc effect).

Cam 2:

Clear flags: don't clear (this is the blur cam)
culling mask: blur
Has Blur (optimized).

Now, if this blur cam is on the back, meaning its depth is LESS than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground.

The issue starts when I set the blur camera's depth higher than the main cam's. In this case, everything gets blurred, no matter that the main cam has no blur effect on it.

Question is, how to set this up so only the desired layers get the blur?


texts: How to spawn GameObject exactly in front of another object?

texts:
I'm working on a 3D game in Unity and I'm having a problem trying to spawn an object exactly in front of a wall in my game, like hanging a picture on it. I don't want the object to look like it's too far from the wall or overlapping the wall.

public void SpawnPrefab(Transform prefab)
{
    compSize = prefab.gameObject.GetComponent<Collider>().bounds.size.z;
    Vector3 mousePosition, targetPosition;
    InputManager inputManager;
    inputManager = prefab.gameObject.GetComponent<InputManager>();
    mousePosition = Input.mousePosition;
    targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,mousePosition.z + compSize/2 + wallSize/2));
    prefab.localPosition = targetPosition;
    if(isAlreadyClicked == false)
    {
        GameObject comp = (GameObject) Instantiate(prefab.gameObject, new Vector3(prefab.transform.position.x, prefab.transform.position.y, prefab.transform.position.z + compSize/2 + wallSize /2), prefab.transform.rotation);
        isAlreadyClicked = true;
    }
}

I tried adding float value on the mouseposition.z like mouseposition.z + <somefloatvalue> but it doesn't seem working like how I wanted because I have different object with different sizes, where some objects spawn at the back of the wall, while some will spawn too far at the front from the wall.

Update: I managed to get the accurate z position for the spawning process, but there's something wrong with its x and y position, it's not spawning based on the mouseclick position.

public void SpawnPrefab(Transform prefab)
{
    clicked = false;
    compSize = prefab.gameObject.GetComponent<Collider>().bounds.size.z;
    Vector3 mousePosition, targetPosition;
    InputManager inputManager;
    inputManager = prefab.gameObject.GetComponent<InputManager>();
    mousePosition = Input.mousePosition;
    targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,mousePosition.z));
    ray = Camera.main.ScreenPointToRay(targetPosition);
    float rayDistance;
    if(plane.Raycast(ray, out rayDistance))
    {
        prefab.localPosition = ray.GetPoint(rayDistance);
        Debug.Log("clicked");
        if(isAlreadyClicked == false)
        {
            OnClickedButton();
            GameObject comp = (GameObject) Instantiate(prefab.gameObject, new Vector3(targetPosition.x, targetPosition.y, frontWall.gameObject.transform.position.z + compSize - wallSize), prefab.transform.rotation);
            isAlreadyClicked = true;
            Debug.Log(clicked);
        }
    }
}

I don't know what is happening...


texts:
the only math I know how is to add the velocity to position. Thats it. i would like to know how to do more stuff, physics, collision detection with stuff other than perfect circles, etc.
But where ever I go online to find source to learn I always end up with something that assumes prior knowledge, which is understandable in a lot of cases. But I don't know where to go to learn math and physics from the absolute beginnings. Also I'm dyslexic, so sites or ressources with just definitions of concepts and no relatable examples wont help that much. So could someone give me some links to books and/or sites that can help me learn math and physics for game development.


texts: How can I calculate the visible area of my camera in world space and take zoom into account?

texts:
I am trying to get the bounds from an orthographic camera in Unity which take into account the current orthographic size (zoom).

I thought that I could use the cameraToWorldMatrix to transform the camera pixel rectangle into world coordinates.

var m = camera.cameraToWorldMatrix;

var bL = m.MultiplyPoint(new Vector3(camera.pixelRect.xMin, camera.pixelRect.yMin));
var uL = m.MultiplyPoint(new Vector3(camera.pixelRect.xMin, camera.pixelRect.yMax));
var uR = m.MultiplyPoint(new Vector3(camera.pixelRect.xMax, camera.pixelRect.yMax));

var rect = new Rect(uL.x, uL.y, Math.Abs(uR.x - uL.x), Math.Abs(bL.y - uL.y));

However, this does not take into account the orthographic size (zoom).

Multiplying the cameraToWorldMatrix with the camera's projectionMatrix property does not give me the correct results either.

Is there a sensible way that this can be solved?


texts:
Which programming paradigm resembles or best suits the Game design or game engine programming?
by paradigm I mean the Imperative, Object oriented, Functional, etc. I came to know that functional programming is more modular than object oriented and is concurrent. is it??


texts: Problem with nested if elements in batch file (text rpg)

texts:
@echo off

:An
@echo Everything has a start...
SET /P _inputname= Please enter your character's name:
SET /P _inputgen= Please enter your character's sex:
set /A hp=10
pause
cls
@echo Your name is %_inputname%
@echo You are a teenage %_inputgen%
pause
cls
@echo This story starts here...
pause
cls
@echo You wake up alone in your room, it's still dark.
@echo 1: Get out of bed
@echo 2: Try to sleep
SET /P _1Dec= What you want to do?
cls
if %_1Dec%==1 (
@echo Now you finally got up. You turned the light on. The first thing you saw was a blinding flash of light.
) else (
@echo You lazily closed your eyes again. It's not morning right now. Why would you get up so early. You managed to fall asleep again easily...
@echo When you finally get up, it's already morning and you can feel all the light even through your closed eyes.But you feel rested and in better mood
set /A hp=%hp%+1
)
@echo Your health: %hp%
pause
cls
@echo Now you can see. But there's one problem. You don't like what you see.
@echo Your mom once said, that you have the most untidy room on the whole world.
@echo But nevermind your mom. The room is quite big, but most of the place is taken by your table, bed and a gigantic wardrobe.
@echo 1: Search around a bit
if %_1Dec%==1 (
@echo 3: Get some sleep
@echo Your health: %hp%
SET /P _2Dec= What do you want to do?
) else (
@echo 2: Go out of your room
@echo Your health: %hp%
SET /P _2Dec= What do you want to do?
)
if %_2Dec%==1 (
@echo First you open your wardrobe.
@echo The first thing you notice (apart from the incredible mess) is a little silver flashlight, currently turned on.
@echo 1: Take it
@echo 2: Let it here
SET /P _2.5Dec= Take it?
if %_2.5Dec%==1 (
set /A flsh=1 >inventory.bat
color 0a
@echo Congratulations! You just received your first item!
@echo Altough it seems basic, use it as wisely as possible…
color 0
) else (
@echo You don’t exactly need a flashlight right now, so why to take it and make your pockets heavier?
)
@echo Once you’ve done everything you wanted, you turn your back on the wardrobe.
@echo You sit to your table, right in front of the giant pile of books and papers.
@echo Taking a look at the book on the top, you recognize a cover of your favourite book,
@echo Looks like you’ll have to sit down and read…
) else (
Pause
)

As it gets to the line with if %_2Dec%==1..it just crashes..
Can someone please tell me why?


texts:
I have a 2D vector (with only X and Y), and my engine only supports orientation through Quaternions.

How do I translate a 2D vector to a quaternion?

The X and Y represent the direction (so X = 0 and Y=1 means going forward, X=0.707 and Y=0.707 means rotate 45 degree, etc).


texts: Procedural Generation of tile-based 2d World

texts:
I am writing a 2d game that uses tile-based top-down graphics to build the world (i.e. the ground plane). Manually made this works fine.

Now I want to generate the ground plane procedurally at run time. In other words: I want to place the tiles (their textures) randomised on the fly. Of course I cannot create an endless ground plane, so I need to restrict how far from the player character (on which the camera focuses on) I procedurally generate the ground floor.

My approach would be like this: I have a 2d grid that stores all tiles of the floor at their correct x/y coordinates within the game world. When the players moves the character, therefore also the camera, I constantly check whether there are empty locations in my x/y map within a max. distance from the character, i.e. cells in my virtual grid that have no tile set. In such a case I place a new tile there.

Therefore the player would always see the ground plane without gaps or empty spots.

I guess that would work, but I am not sure whether that would be the best approach.
Is there a better alternative, maybe even a best-practice for my case?