texts: Consistent normals at any angle in bezier curve

texts:
Could not work out or find any solution for this.

I have a spline which consists of bezier curves (in 3d space) — in fact, any straight line will also have such problem.

I take a point on the curve and need to get a normal to this point at any given angle 0 - 360 (say, to build a mesh around it or to calculate an offset for the movement).

I understand that in 3d space we have to define a plane to build normal, normally — by using Vector3.Cross(A, B); In general, one uses curve's tangent as A and, e.x., Vector3.up or right as B.

But, if curve becomes vertical (it can go in any direction, imagine any track that is ground-independent, like in space), it gets aligned with Vector3.up, and the direction of normals goes crazy, swaps direction and so on, which is quite logical. More, it does so not only in straight vertical position, but start to change gradually around it.

So, the question is: how can I get consistent (all in equally correct direction) normals, using any given curve point position and angle for normal rotation?

Update:

The initial approach looked like this:

public Vector3 GetTangent(...) {

    Vector3 q2 = CalculateTangent (...);

    Quaternion lookAt = Quaternion.LookRotation (q2);
    Vector3 normal = lookAt * Vector3.up;
    normal = Quaternion.AngleAxis (angle, q2) * normal;
    return point + normal * size;
}

Which generated the following normals (blue is up):

Now, if I try to use the previous normal for the direction:

Quaternion lookAt = Quaternion.LookRotation (q2, previousNormal);

first of all, I don't understand what to place here:

Vector3 normal = lookAt * ?

And any combination of tangent, normal and rotation gives me something like this:

Where it can be clearly seen that normals on the vertical are improved (though not correct), but on the horizontal all went wrong, as if I just changed Vector.up to Vector3.right.

In addition, the code for generating the tube in its main part looks like this:

float vStep = (angleTo - angleFrom) / pipeSegmentCount;
if (b == 0 && _tP == 0f) _tP = 0.01f;
if (b == 0 && _t == 0f) _t = 0.01f;
if (b == spline.Nodes.Count - 2 && _tP == 1f) _tP = 0.9f;
if (b == spline.Nodes.Count - 2 && _t == 1f) _t = 0.9f;
Vector3 vertexA = spline.GetTangent (_pP, _tP, _bP, Vector3.up, pipeAngle, pipeRadius);
Vector3 vertexB = spline.GetTangent (_pointsTotal[b] [s], _t, b, Vector3.up, pipeAngle, pipeRadius);
for (int v = 1; v <= pipeSegmentCount; v++, i += 4) {
    vertices [i] = vertexA;
    vertices [i + 1] = vertexA = spline.GetTangent (_pP, _tP, _bP, Vector3.up, v * vStep + pipeAngle, pipeRadius);
    vertices [i + 2] = vertexB;
    vertices [i + 3] = vertexB = spline.GetTangent (_pointsTotal[b] [s], _t, b, Vector3.up, v * vStep + pipeAngle, pipeRadius);
}

Where 0.01f and 0.99f are because ends of spline do not have control points and LookRotation produces an error about zero rotation. b and _bP are node indexes, and _P suffix is for "previous".

This particular code is used to generate a round rail and move an object beneath it. Thus, it is important that the bottom normal is consistent and always at the bottom (when it is vertical, this bottom is not the world bottom of course, but it protrudes at the side of the tube, object will turn itself accordingly, looking forward the curve).


texts: Differences between Unity/UE shaders and Opengl Shaders

texts:
At first, I thought that they are the same, shaders in game editor write by programmers(or use some graph flow tools nowadays) just get compiled into opengl shaders.

But now I'm writing my own render engine, and found that my engine's shader should not be replaced, since it will do the coordinate transformations.

So, is a shader in Unity/UE the same thing as a shader is in Opengl?

In other words, does the shader in game editor directly change the shaders in the pipeline, or it just use some technical to insert into the render's own shaders?


texts: Restrict object movement inside irregular shaped container

texts:
I want to restrict object movement inside an area. My object follows cursor position.

I have already done that for the area border using Mathf.Champ to the translate because the borders are square shaped (got the idea from Unity: Restrict movement inside a gameobject (2D)). The thing is that inside the box area there can also be other shapes (colliders) which I don't want my object to go over.

I know people suggest using physic collisions, but my game needs a unit perfect positions so I can't use physics due to physics' default contact offset (the one physics use to detect collisions).

Here is a short video of what I have:

https://gfycat.com/cookedsmartannelid

As you can see, movement is restricted (clamped) inside the box area but I want the movement to also be restricted to not go over the black area.

Is there a way to be able to do this with just clamping or do I need a raycast system or something like that?


texts: OpenGL RayCasting and Intersection with plane

texts:
I have been trying for a couple of days to raycast. I have a Renderable/Texture/Primitive/Whatever placed in the WORLD at 0.0f,0.0f,0.0f, and when I click the mouse I want to know at what X,Y coordinates was the Primitive "clicked". We can safely assume that the primitive will always be at Z=0;

Basically, I should do raycasting. But it does not work. I tried finding the 3D position of the ends of the ray(near/far plane), and then compute the intersection, but it does not work. I tried getting Z from the DEPTH BUFFER,  but I always get 0 and it still does not work.

Does anyone have any fast, simple method for this?


texts: 3D models budget. What matters more number of triangles or vertices

texts:
When I am making a model for a 3D game what should I take as a measure in my budget Polygons (triangles) or vertices?  I have made an experiment with two sets 40000 cubes one with 8 vertices and 12 triangles, another with 24 vertices and 12 triangles. All was done in Unity and both of those were generated procedurally. To my surprise, both sets performed almost the same there was a very small difference between them.

Does it mean I should not worry about vertices count and only look at triangles count?

EDIT:
I have made another experiment I have created a plane with 19602 triangles and 10000 vertices and another one with same ammount of tirangles  but 39204 vertices. I have generated 4000 of both. Now less vertices won 14 fps to 19 fps.  So I guess generally less is better, but only in large differences.


texts: I just made a game using Unity. However, when I tested the game on unity remote, the resolution or graphic of the game was really low compared to the actual game. Would this change when I deploy the game or do I have to tweak the settings? If I have to tweak the setting, can you guys tell me what to tweak.


texts: Access buttons individually made by a for loop (old Unity GUI, Unity Editor script)

texts:
I've got a problem and I am struggling with this for a couple of days now.

I am making an Editor script and I want to access buttons individually when
created by a for loop. There is a public class ButtonNode which stores some variables
of the button like name and size.

public class ButtonNode
{
    public bool button;
    public string name = "O";
    public float sizeW = 25f;

    public void AlterButton()
    {
        name = "P";
    }
}

Then there is my Editor script in which I create the buttons. This is where I get stuck,
how do I access these buttons individually? For example, I want to change the name of the button
when that button is clicked. How do I do that? Because they are booleans (I don't
really know why, this is the legacy GUI) I can't access the transform.name components etc).

public static ButtonNode[] bn = new ButtonNode[10];

void OnGUI()
{
    GUILayout.BeginHorizontal();

    for (int i = 0; i < bn.length; i++)
    {
        bn[i] = new ButtonNode();
        if (bn[i].button = GUILayout.Button(bn[i].name + i, GUILayout.Width(bn[i].sizeW)))
        {
            bn[i].AlterButton();
        }
    }

    GUILayout.EndHorizontal();
}


texts: What image resoluiton for sprites in 2D mobile game?

texts:
I am an experienced iOS developer, however I have never worked on games before. We are planning to make a mobile game using Unity 3D.

Our graphics designer needs to know what resolution should he design our sprites in? I know that we will have to use different sizes for the different screen resolutions, but my question is:

What is the largest resolution we will need the sprites to be in, considering future-proofness?

OR

Shall we go with vector graphics?

We are targeting tablets as well!


texts: Maya loading custom attributes from file

texts:
I am trying to use Maya as my level creator. I have created some custom attributes for objects to use, and saved them out (into a .mel file). However, when I try to apply this preset to an object, the only values it uses are values intrinsic to Maya, such as traslation and scale.

The documentation on this subject is very sparse and there doesn't seem to be much information on this, so any help would be greatly appreciated.


texts:
I am creating a game like ruzzle but i am creating for web . Initially my basic task is to display the alphabets in the html5 canvas the letters should fetched from the database randomly in the html5 canvas tiles and when the user create the word just like in ruzzle , the new words add randomly in the html5 canvas .

Should I use easeljs or any other technology . I also want to include multiplayer gaming both friends can simultaneously play the game with each other.


texts: Keeping track of focused widget in GUI tree

texts:
I'm designing a GUI framework based on trees of widgets.  Widgets are general control and container structures that are everything from panels to buttons to file dialogs.  Widgets have an array of child widgets; a button contains a label and maybe an icon.  Widgets are fed input events where the widget first does its own logic with the event then passes it on to its children.  The application feeds input events to a single root widget, which can be anything from a single button in the middle of the screen to a full control window.

I need a way to handle which widget(s) receives keyboard events.  I've decided that one of the widgets in a given widget tree would be the focused widget.  Widgets would have a gainFocus method and a loseFocus method, which would be used in response to mouse click events or manually by the application.  It's unlikely I'll implement tabbing.  When one widget gains focus, any existing focused widget would naturally lose focus.

I still want each ancestor of the focused widget to see a given keyboard event in turn before it's given to the focused widget itself.  So if I have a panel with a text box in it, the panel would see the event before the text box does.  Therefore I really need to keep track of the chain of widgets from the root widget to the focused widget.  I also need to maintain data integrity when I change focus so that all widgets in a tree can correctly tell whether or not they're the focused widget or an ancestor of the focused widget.

I've so far come up with giving widgets a hasFocus boolean and a focusedChildIndex integer.  hasFocus would be set to true when the widget has focus.  focusedChildIndex would be set to the index of the focused child in its child array, which could be the focused widget itself or the next widget in the chain leading to the focused widget, or -1 to indicate that there's no focused child.  Setting these variables when one widget in the tree gets its gainFocus or loseFocus method invoked is something I'm stumped on though.

Edit

So we're clear, this is what I think my widget class will be like:

class Widget
    private Widget parent
    private Array<Widget> children

    // Methods for getters, adding widgets to widget trees, etc.
    ...

    public void mouseClick(int x, int y)
        doMouseClickEvent(x, y)
        for c in children
            c.mouseClick(int x, int y)

As you can see in mouseClick the widget sees the event before its children does.  I want keyboard inputs to work the same way, except this time I want to only have a single chain from the root to the focused widget to see the event.  Plus I need to make sure that when one widget gains focus the currently focused widget in the tree loses focus.


texts: What game engine should I use to mock around?

texts: I'm a software engineer student (about to start my 2nd year) and I did really enjoy last years object-oriented programming and working with Java (greenfoot and later eclipse) to make simple games. I would really like to delve deeper in to software development and can't wait for 2nd year of college to start ,so I mocked a bit in eclipse and boy writing all of the game engine is hard and takes a lot of time, so maybe anyone knows an easy game engine just to mock around and explore game development for fun ?


texts: Spawning projectile: it's there but does not show

texts:
Here is the code and very simple.
I can see the object in the blue print and has nothing except the object itself.
so all the issue should be on the C++ code.
UCLASS(config=Game)
class APiramidShootingProjectile : public AActor
{
    GENERATED_BODY()

    /** Sphere collision component */
    UPROPERTY(VisibleDefaultsOnly, Category=Projectile)
    class USphereComponent* CollisionComp;

    /** Projectile movement component */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
    class UProjectileMovementComponent* ProjectileMovement;

public:
    APiramidShootingProjectile();

    /** called when projectile hits something */
    UFUNCTION()
    void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);

    /** Returns CollisionComp subobject **/
    FORCEINLINE class USphereComponent* GetCollisionComp() const { return CollisionComp; }
    /** Returns ProjectileMovement subobject **/
    FORCEINLINE class UProjectileMovementComponent* GetProjectileMovement() const { return ProjectileMovement; }

};

and the C++ (without the hit portion)
APiramidShootingProjectile::APiramidShootingProjectile()
{
/*  SetRemoteRoleForBackwardsCompat(ROLE_SimulatedProxy);
    bReplicates = true;
    SetReplicatingMovement(true);
    */
    // Use a sphere as a simple collision representation
    CollisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
    CollisionComp->InitSphereRadius(5.0f);
    CollisionComp->BodyInstance.SetCollisionProfileName("Projectile");
    CollisionComp->OnComponentHit.AddDynamic(this, &APiramidShootingProjectile::OnHit);     // set up a notification for when this component hits something blocking

    // Players can't walk on it
    CollisionComp->SetWalkableSlopeOverride(FWalkableSlopeOverride(WalkableSlope_Unwalkable, 0.f));
    CollisionComp->CanCharacterStepUpOn = ECB_No;

    // Set as root component
    RootComponent = CollisionComp;

    // Use a ProjectileMovementComponent to govern this projectile's movement
    ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileComp"));
    ProjectileMovement->UpdatedComponent = CollisionComp;
    ProjectileMovement->InitialSpeed = 3000.f;
    ProjectileMovement->MaxSpeed = 3000.f;
    ProjectileMovement->bRotationFollowsVelocity = true;
    ProjectileMovement->bShouldBounce = true;

    // Die after 3 seconds by default
    InitialLifeSpan = 1000.0f;

    //For Multiplayer
    //bReplicates = true;
}

so here all that should be shown is created, but nothing shows, even so when i aim something the hit function works and works as it should, so really not understanding what its happening.
I am new to this and extremely frustrated so please answer as soon as possible.


texts: Game engine design: Multiplayer and listen servers

texts:
My game engine right now consists of a working singleplayer part. I'm now starting to think about how to do the multiplayer part.

I have found out that many games actually don't have a real singleplayer mode, but when playing alone you are actually hosting a local server as well, and almost everything runs as if you were in multiplayer (except that the data packets can be passed over an alternate route for better performance)

My engine would need major refactoring to adapt to this model. There would be three possible modes: Dedicated client, Dedicated server and Client-Server (listen mode)

How often is the listen-server model used in the gaming industry?
What are the (dis)advantages of it?
What other options do I have?


texts:
I'm making a little RPG multiplayer game where each player can travel long distances. Traveling from point A to B can take up to 10 minutes and – once initiated – is an automatic process. Now, I am not quite sure how to go about this on the server-side, the server has to be the one telling the clients that the traveling player has arrived or not.

Do I have to run some sort of timer where I check every X seconds/milliseconds if all the traveling players have reached their destination in order to update the DB? (the characters are saved on the server to prevent cheating).

The way I imagined it was simply to capture the timestamp at the start of travel, then use the distance to calculate what the time should be when the player will arrive, and then run some sort of timer that checks each traveling players "start time" , "actual time" and "destination time", but since I have never done this before I'm not sure if this is a good way of doing it?


texts: Unsure how to change sprites in an animation (Unity)

texts:
I'm using Unity 2019.3.13f1 to make a 2D game with friends and I am looking for help with changing sprites so that different characters can look different.  Currently we have sprites for hair, heads, armor, etc... in different sprite sheets, labeled hair1, hair2, etc. so we can add more as we go.  We have also created a prefab "unit" with children for each different part so that we could set each piece of the unit to have a different sprite renderer.

I created an animation that had the different sprites manually added and keyframed, but I cannot figure out any way to create a sort of default animation that could be fed something like "Use hair1 for the hair, head3 for the head, armor2 for the armor for this unit's animations".  I watched a video from back in 2014 that used a script to change which sprite sheet was used for the animator, but they had one sprite sheet that contained all of the parts, rather than the mix and match approach.  Additionally, I have the animator set up so that the unit goes between different animations appropriately, but again, the only way I currently understand it involves me manually creating each animation.

I'm honestly at a complete loss at this point, so any assistance would be greatly appreciated.


texts: Is WS-Security or REST+SSL a scalable authentication platform?

texts:
I'm trying to find a solid architecture for authenticating users against a database. I have a game client, which I plan to serve up a request with. The transport doesn't really matter, but at this point I'm thinking HTTP and leveraging either SSL or WS-Security to ensure the encryption of data over the wire.

I'd like to avoid middle-man attacks if possible so I'm leaning towards WS-Security even though I know it costs more in terms of overhead.

On the service side, I'd like to use an authentication framework such as Apache Shiro to authenticate users against a MySQL database. I'm not sure if I can leverage the session features or not, as I haven't looked that for into it, but it'd be great if I could.

It will probably be a mix of storing some session information in the database and if I can leverage Shiro's session features then that's a bonus.

My real question is about the handshake between the client and server. If I use WS-Security isn't all that taken care of for me? Does that alone make the overhead worth it?

If not, what should I do here? I want to make sure all of the requests from the client are authenticated but I also don't want to have to jump through hoops to make it happen. Would something as simple as HTTP digest authentication work here?

One constraint I have is access to libraries. If it's not free and can't be used in a commercial product then I can't leverage it. My client is going to be written in C++ and I can use whatever language makes it easiest (I'm leaning towards Java) to make it happen on the server side.

I plan on adding support for users to purchase in-game items through micropayments down the road, so this handshake mechanism definitely needs to be secure.

I keep hearing people suggest REST + SSL, and to examine Amazon's Signing and Authenticating REST Requests page. Is that a viable alternative? If I used that and something like Apache Shiro would I have a winner?


texts: i want to upload to 2gb model animation to vram with VBO technic but i am getting this error with nvidia (with amd no error)

texts: when i try to work with amd its working with amd hd6870 and ati x1550 but when i try to work with gtx 950 its giving this error. if i upload less than 2gb example 300mb then its working but i want to upload 2gb. what can i do ? sorry for bad english.


texts:
I would like to know how is the typical collision detection of most games. For example, you control a character which can move in 2 dimensional directions (except up and down). Now lets asume he walks into a wall, most of the games depending on character angle and the BB normal face will only stop the player in one axis, but will continue moving in the other along the wall axis. How is that done?

I've only managed to stop the character from going through the wall by seting the position to the last one in the past frame if the new position colllisions the bounding box. But this just makes the player stop sharply and unrealisticly.


texts:
Recently I have been working with OpenGL and have decided to use colors instead of textures. However, since the project I am working on is going to have a low-poly look, I want each color to stand out, and not be drawn as a gradient like OpenGl usually does.
The problem I am having is with the  flat modifier. While it does give the nice non-gradient look, it uses a provoking vertex, which is not not good in this case.
Here is an example of what I got and what I wanted:
(original link)
I tried looking into different solutions, and the one I think would work would be to store one color per face. However, I am not sure how to do that. Any suggestions are appreciated.
Thanks!


texts: unity webgl scale page on different sizes of internet browsers on pc or phone

texts:
unity only has a fixed resolution for building webgl. how can I make it changebale on users browser size change.

there are some tutorials on the internet that doesn't match. there is only

    index.html unityloader.js
    gamename.json  gamename.data.unityweb  gamename.asm.memory.unityweb
    gamename.framework.unityweb  gamename.asm.code.unityweb

how can I make multi res webgl output happen for unity?


texts: Should calculations be done on the CPU or GPU?

texts:
I'm currently learning OpenGL and it's become obvious that I can do most calculations on the CPU or the GPU. For example, I can do something like lightColor * objectColor on the CPU, then send it to the GPU via a GLSL uniform. On the contrary, I can send them separately and have GLSL perform the calculation.

Is there a best practice on where graphic calculations should be performed? My thoughts are that the GPU might be optimized for matrix or vector calculations. However, I'm also thinking that the CPU might be a better place for it since the GPU might have better things to do.


texts:
I'm trying to understang how can I improve bloom effect quality using all known to me optimizations.

Currently I'm making it as follows:

Create new texture using some threshold to extracts areas which should glow
Downsample that texture 4 times (using bilinear filtering - GL_LINEAR)
Blur each texture horizontally using 5x5 gaussian blur.
Blur each texture vertically using 5x5 gaussian blur.
Composite each blurred texture with final image.

I've implemented gaussian blur using Incremental Gaussian Algorithm and set radius to 5. However because of size of last texture after composition bloom has very low quality especially when moving camera:

It doesn't look clear here but you can see it near bunny tail.

Simple workaround to that issue was increasing the radius for smaller textures but then image was more blurred.

Similar effect is when I use solution presented by Philip Rideout.

I get better results when I use blur shader presented here. However I still see some kind of vertical stripes.

I also tried to improve the algorithm by blurring the image and then downsampling it. Then I repeated whole process for the rest of images. But I haven't spotted any difference.

I'm also wonder how it is done in Unreal Engine. I mean how effective blur radius is computed. Documentation claims that each Bloom Size value is "the size in percent of the screen width" and each texture is smaller from previous one 2 times.


texts:
I am drawing blocks of various amino acids (array of aminoacid objects), where one line of amino acids represents one sequence.

aminoacid class:

public void renderShape() {
    shaperenderer.setProjectionMatrix(cam.combined);
    shaperenderer.begin(ShapeType.Filled);
    shaperenderer.setColor(cc.getR(), cc.getG(), cc.getB(), 0);
    shaperenderer.rect(xpos, ypos, aawidth, aaheight);
    shaperenderer.end();
}

public void renderBatch() {
    batch.setProjectionMatrix(cam.combined);
    batch.begin();
    font.setColor(Color.BLACK);
    font.draw(batch, name, xpos+Game.AAFONTOFFSETX, ypos+Game.AAFONTOFFSETY);
    batch.end();
}

Now I need a way to drag and drop feature to move the individual blocks. How can I do this? Can I use the DragAndDrop class of libGDX? If so, how should I do it??

As a side note, I found a way to do it without libGDX:

public class AminoAcidDragAndDrop extends JFrame {
  private String brr_A = "EAQITAPFELSAFTGRPEWI";
  private JTable table;
  private DefaultTableModel tableModel;

  private DefaultTableModel getDefaultTableModel() {

    String[] cols = new String[brr_A.length()];
    for (int i = 0; i < brr_A.length(); i++) {
      String currentAminoAcid = String.valueOf(brr_A.charAt(i));
      cols[i] = currentAminoAcid;
    }

    return new DefaultTableModel(null, cols);
  }

  public AminoAcidDragAndDrop() {
    super("Amino Acid Drag and Drop Demo");

    tableModel = getDefaultTableModel();
    table = new JTable(tableModel);

    JScrollPane sp = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    getContentPane().add(sp, BorderLayout.CENTER);
    getContentPane().setPreferredSize(new Dimension(1024, 768));
  }

  private static void createAndShowGUI() {
    // Create and set up the window.
    AminoAcidDragAndDrop test = new AminoAcidDragAndDrop();
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Display the window.
    test.pack();
    test.setVisible(true);
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        // Turn off metal's use of bold fonts
//              UIManager.put("swing.boldMetal", Boolean.FALSE);
        createAndShowGUI();
      }
    });
  }
}

Can I convert it for libGDX? If so, how?

I also tried it with Actors but how can I use an Actor array? Would an ArrayList<> work?

Now I can move the first aminoacid, but DragAnDrop needs a final int. How can I solve this for all aminoacids?

public void drop (Source source, Payload payload, float x, float y, int pointer) {
    aminoacidlist.get(aaiddnd).setBounds(aminoacidlist.get(aaiddnd).getXpos()+Game.AAWIDTH, aminoacidlist.get(aaiddnd).getYpos(), Game.AAWIDTH, Game.AAHEIGHT);
    minoacidlist.get(aaiddnd+1).setBounds(aminoacidlist.get(aaiddnd+1).getXpos()-Game.AAWIDTH, aminoacidlist.get(aaiddnd+1).getYpos(), Game.AAWIDTH, Game.AAHEIGHT);
}

The compiler tells me:

  aaiddnd cannot refer to a non-final local variable.


texts: PYGAME - Sprite movement seize to function when entire X and Y span is reviewed

texts:
I've created an sprite class that has a detection radius checking if the player enters the zone. If yes, the sprite moves towards the player. It works perfectly fine when the sprite checks for three directions (X is greater, X is lower, Y is greater/lower), in other words, the sprite only moves up and down if all four directions are enabled..
Here is my code for the move function:
def move(self):
        target_x, target_y = self.target.pos

        if self.mob_wc + 1 <= 24:

                if self.pos_x < target_x:
                    self.vel += vec(self.speed, 0)
                    self.image = self.game.orc_mob_walkRight[self.mob_wc//6]
                    self.mob_wc += 1

                elif self.pos_x > target_x:
                    self.vel = vec(-self.speed, 0)
                    self.image = self.game.orc_mob_walkLeft[self.mob_wc//6]
                    self.mob_wc += 1

                if self.pos_y > target_y:
                    self.vel = vec(0, -self.speed)
                    self.mob_wc += 1

                elif self.pos_y < target_y:                   <-- if this condition is disabled
                    self.vel = vec(0, self.speed)                 The sprites move perfectly upwards
                    self.mob_wc += 1                              towards the player, shifting between
                                                                  moving On X and moving on Y.
        else:                                                     However, if it is enabled, the
            self.mob_wc = 0                                       sprites ONLY move on the Y field

Here is my code for the update function:
    def update(self):
        self.rect = self.image.get_rect()
        self.rect.center = self.pos
        self.pos += self.vel * self.game.dt

        self.pos_x, self.pos_y = self.pos

        target_dist = self.target.pos - self.pos

        if target_dist.length_squared() < self.detect_radi**2:
            self.move()
        else:
            self.vel = vec(0,0)
            self.image = self.game.orc_mob_img

For the way they move i followed this post.
I am aware my build differs due to the use of vectors, which is something that i'm suspecting may be the cause of the issue. If anyone have any idea or tips to why this issue may occur, please tell me cause i've been sitting trying to fix this for 3+ hours now..


texts: How to run 'Call in Editor' Functions that are implemented in Level Blueprints?

texts:
I have a Blueprint Function within a Level Blueprint, marked as Call In Editor.

How can I run CallInEditor functions in Level Blueprints?


texts: Whats the best way to expose current settings to your classes?

texts:
Just as the title states, whats the best way to expose current settings like resolution to my classes?
(I know this might have been asked, but I couldn't find anything)

I was thinking of the service-locator design pattern, but I am unsure, as I read that it can be abused easily.( I mean it might not fit this particular use-case )


texts: WWW(Unity) with HTTPS on Android not working

texts:
I'm using a native android plugin my team made for communication with a server, and as it uses HTTPS I use a certificate with it. Everything's fine with that, the problem is that, in Unity, when I try to use WWW with anything HTTPS, I get this error

  V/com.facebook.unity.FB: sending to Unity OnLoginComplete({"error":"Caught exception: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.","callback_id":"5","key_hash":"XXXXXXXX"})

I get this error in particular when trying to use the Facebook SDK to post a picture to the user's timeline. Looking at the source code, it uses Unity's WWW for the POST.
If in Unity I never call my native plugin's methods, then everything works nicely.
Is there any way to get around that? Somehow install another certificate? Use some different header?
Any help would be great, thanks.


texts: How can I completely hide and protect strings from the player in Unity?

texts:
I have been using Unity to create a 2D game which will be completely offline (which is the problem), the game-play needs you to enter certain strings at certain levels and Unity compiles to DLLs, which can be easily reverse engineered, so is there a way to protect those strings (the game is offline so I can't retrieve from other source)?

The game relies heavily on those strings, and yes I'm aware of Obfuscation but I want something more robust. And I know that the easy way out would be doing everything online from a data-source but I was wondering if it's possible.

It can be decompiled like this:


texts: Setting Orientation of Character in Bullet/Ogre

texts:
I've been suffering from an issue regarding the implementation of orienting characters in a game I'm implementing using Ogre3D and Bullet physics.

What I have: A Direction Vector that the character is moving in, along with its current orientation.

What I need: To set the orientation of the character to face the way it is moving.

I have a snippet of code that sort of does what I want:

btTransform src = body->getCenterOfMassTransform();
btVector3 up = BtOgre::Convert::toBullet(Ogre::Vector3::UNIT_X);
btVector3 normDirection = mDirection.normalized();
btScalar angle = acos(up.dot(normDirection));
btVector3 axis = up.cross(normDirection);
src.setRotation(btQuaternion(axis, angle));
body->setCenterOfMassTransform(src);

Where 'body' is the rigidbody I'm trying to orient.

This snippet has a couple of problems however:

1) When changing direction, it tends to 'jitter' i.e. it rapidly faces one way, then the opposite for a second or so before correcting itself to the orientation it is supposed to be at.

2) Most times that the code is run I get an assertion error from Bullet's btQuaternion on

assert(d != btScalar(0.0));

Can anyone help?

Thanks!


texts: Show world space UI object on top of the Mesh

texts:
I want to show object name whenever mouse over happens on a certain object and here is my code snippet that trying to place World space UI image object on top of the object.

private void OnMouseEnter()
{
    if (!EventSystem.current.IsPointerOverGameObject())
    {
        Vector3 topPosition = MeshTopPoint.GetMeshTopPoint(this.gameObject);
        partNameImage.transform.position = topPosition;
    }
}

but the problem is it is not placing the object on center top of the object instead of it like this (placing UI on the corner):

And here is my mesh top position get function:

public class MeshTopPoint : MonoBehaviour
{

    // Update is called once per frame
    public static Vector3 GetMeshTopPoint(GameObject go)
    {
        Vector3 worldUp = go.transform.InverseTransformDirection(Vector3.up).normalized;
        Plane p = new Plane(worldUp, Vector3.zero);
        Vector3[] verts = go.transform.GetComponent<MeshFilter>().sharedMesh.vertices;
        Vector3 topVertex = Vector3.zero;
        float maxDist = float.NegativeInfinity;
        for (int i = 0; i < verts.Length; i++)
        {
            float dist = p.GetDistanceToPoint(verts[i]);
            if (dist > maxDist)
            {
                maxDist = dist;
                topVertex = verts[i];
            }
        }

        topVertex = go.transform.TransformPoint(topVertex);
        return topVertex;

    }
}

Here is my UI Image:


texts: I have learned how to create and manage threads in C++. Now I'm trying to create game loop based on multithreading but I can't imagine how should I split whole game to tasks. I mean, should rendering be separated from updating physics?


texts: Inputting Only Alphabetical Input - Slick2D

texts:
I'm trying to obtain the user input for when they enter their own name. However I would prefer to have it Alphabetically.

This is what I'm doing at the moment:

    if (input.isKeyDown(Input.KEY_A)) {

    }
    if (input.isKeyDown(Input.KEY_B)) {

    }
    if (input.isKeyDown(Input.KEY_C)) {

    }
    //continued for each letter.

Is there an easier way to obtain the input? An hopefully make sure its only alphabetical?


texts: XNA 3rd Person Camera - pitch reverses when facing backwards?

texts:
I have a 3rd person camera which rotates around the Y axis fine (yaw) and when I am facing forward (0, 0, -1) moving the mouse up moves the camera up and down great. But the more I turn the player and camera the the less the camera moves up and down until I get to 90 degrees where it almost stay still and at 180 it moving the mouse up moves the camera down!

Any ideas? How should I be calculating camera pitch? The player only yaws - it does not roll or pitch. The camera yaws and pitches. The cameras update method looks like:

    public void Update(Vector3 playerPos, float pitch, float yaw)
    {
        Matrix rotation     = Matrix.CreateRotationY(yaw) * Matrix.CreateRotationX(pitch);
        Vector3 newOffset   = Vector3.Transform(offsetAmount, rotation);

        cameraPos   = playerPos + newOffset;
        View        = Matrix.CreateLookAt(cameraPos, playerPos, Vector3.Up);
        Projection  = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Constants.AspectRatio, Constants.NearClip, Constants.FarClip);
    }


texts: The question is simple, but I can't resolve it for a couple of days. I have an enemy model with ragdoll attached and also a couple of animations(e.g. idle, walk, run). It seems that ragdoll work only when animator is stopped and vice versa. What I want is when the animation is playing all the forces are applied too, e.g. when I shoot enemy he still walking by animation and and ragdoll corresponds with AddForce(). I tried to find appropriate tutorial for that, watched ton of youtube videos and read a lot of unity forums, but no success. Any help is appreciated. Thanks in advance.


texts: How can I create a 2D sprite shadow like in "Alto's Odyssey"?

texts:
I've seen that the game "Alto's Odyssey" has a very nice way of projecting shadows on the ground the player is sliding on:

How could i replicate that?
Would I use some shader magic, or by projecting a 3D mesh/image on the ground plane?


texts: Extrapolation breaks collision detection

texts:
Before applying extrapolation to my sprite's movement, my collision worked perfectly.  However, after applying extrapolation to my sprite's movement (to smooth things out), the collision no longer works.

This is how things worked before extrapolation:

However, after I implement my extrapolation, the collision routine breaks.  I am assuming this is because it is acting upon the new coordinate that has been produced by the extrapolation routine (which is situated in my render call ).

After I apply my extrapolation

How to correct this behaviour?

I've tried puting an extra collision check just after extrapolation - this does seem to clear up a lot of the problems but I've ruled this out because putting logic into my rendering is out of the question.

I've also tried making a copy of the spritesX position, extrapolating that and drawing using that rather than the original, thus leaving the original intact for the logic to pick up on - this seems a better option, but it still produces some weird effects when colliding with walls.  I'm pretty sure this also isn't the correct way to deal with this.

I've found a couple of similar questions on here but the answers haven't helped me.

This is my extrapolation code:

public void onDrawFrame(GL10 gl) {

        //Set/Re-set loop back to 0 to start counting again
        loops=0;

        while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){

        SceneManager.getInstance().getCurrentScene().updateLogic();
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;
        tics++;

     }

        extrapolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks;

        render(extrapolation);
}

Applying extrapolation

            render(float extrapolation){

            //This example shows extrapolation for X axis only.  Y position (spriteScreenY is assumed to be valid)
            extrapolatedPosX = spriteGridX+(SpriteXVelocity*dt)*extrapolation;
            spriteScreenPosX = extrapolationPosX * screenWidth;

            drawSprite(spriteScreenX, spriteScreenY);

        }

Edit

As I mentioned above, I have tried making a copy of the sprite's coordinates specifically to draw with.... this has it's own problems.

Firstly, regardless of the copying, when the sprite is moving, it's super-smooth, when it stops, it's wobbling slightly left/right - as it's still extrapolating it's position based on the time.  Is this normal behavior and can we 'turn it off' when the sprite stops?

I've tried having flags for left / right and only extrapolating if either of these is enabled.  I've also tried copying the last and current positions to see if there is any difference.  However, as far as collision goes, these don't help.

If the user is pressing say, the right button and the sprite is moving right, when it hits a wall, if the user continues to hold the right button down, the sprite will keep animating to the right, while being stopped by the wall (therefore not actually moving), however because the right flag is still set and also because the collision routine is constantly moving the sprite out of the wall, it still appear to the code (not the player) that the sprite is still moving, and therefore extrapolation continues.  So what the player would see, is the sprite 'static' (yes, it's animating, but it's not actually moving across the screen), and every now and then it shakes violently as the extrapolation attempts to do it's thing....... Hope this help


texts:
I have a custom Awesomium::Surface implementation, and I need to create a Scroll function for it. The function asks me to manually move some pixels of my texture by the indicated X and Y offset.

How can I move/access pixels inside a SDL_Texture since SDL_LockTexture() provide write-only pixels?


texts: How to create realistic 2d lighting using colour temperature

texts:
I'm looking for a lighting algorithm that produces realistic lights expressed in kelvins, from about 2500k to 6500k. What I'm confused about is how to make the lights properly interact with the colors of game objects.

If a whole level is fully lit (overcast daylight) then it would seem that I should use just the color of the object. But what if I'm in a closed room with no windows, and there is an incandescent bulb shining light in the room? How would that light properly light up the objects in the room?

There does not seem to be an obvious solution to the problem. And simply mixing the color of the light with the colors of the object, seems an inaccurate approach.


texts: What are the pros and cons of HLSL vs GLSL vs cg?


texts: Set Non-Looping Animation Time to Seconds

texts:
I have an animation that does not loop.  It plays for the default duration (n seconds), then stops on the last frame.  This is exactly what I want to have happen, but I want it to play for m seconds, not n seconds.  I do not know how long n seconds is.

I have to get it exactly to m seconds, because it is a changing variable.  So estimating will not work.  I need it to match up exactly with another animation.  How can I stretch an animation to last an exact number of seconds?


texts: Using a programmable pipeline in a game engine

texts:
As a learning experience, I'm developing my own 3D game engine using OpenGL. I'm a little confused as to how to implement my rendering engine such that it uses a programmable pipeline while still being responsible for projecting and displaying vertices correctly.

Let's say my engine has a simple vertex shader that uses projection and modelview matrices to project a vertex in 3D space. How do I use the engine's vertex shader while still allowing the programmer to provide his/her own vertex shader for other calculations in their game? What is the normal approach here?


texts:
Whenever I run my game using the DesktopLauncher I am able to find my files, but if I build an executable using Gradle I get an error that the files are not within the specified folder.

This may be linked to the fact that for some reason the assets I place into the Android project's asset folder, which is linked to my Desktop project, are being placed in the bin folder of my Desktop project. Currently to get around this I have a check that looks for whether I am executing as an Android game or Desktop (and applies a prefix accordingly, either "bin" or "").


texts: Regarding sprite design and resolution for tablets and phones

texts:
I am about to start working on a game for android devices, in my spare time, to get familiar with android development. I'm more interested in using the best practices possible than getting a quick result, and that is why I need some guidance regarding graphics.

I think the game is going to be fully sprite based. Everything is going to be in .bmp form, or something similar, and my question is:

Should I design the sprites in a small resolution (ie for phone screens) and scale them up to fit into larger screens (tablet screens), should I do it vice-versa or should I consider a completely different approach? Would designing a different set of sprites for each of the most used resolution settings be worth it or are there simpler solutions to the problem with fewer drawbacks than the ones I mentioned above? (If I follow the first approach, for example, the larger the screen the worse the graphics will get, since every pixel of the original drawing will cover several pixels on the screen). Is there a standard approach for dealing with this kind of problems?

If you need me to be more detailed or more clear about something I mentioned (or forgot to) please don't hesitate to ask. Also, excuse me for any inaccurate use of the English language.

Thank you in advance for your input.


texts: In Unity3D, how do I move the camera with the mouse without spinning it on its axis when looking down/up?

texts:
I'm currently trying to recreate how Space Engineers work with their first-person acmera in Unity 3D. I'm currently stuck on how to make sure the camera doesn't spin around its axis when looking downwards or upwards, like a sphere. I've looked through several available online snippets for assistance however they all use quaternion to rotate their camera around an axis; this isn't what I want.

Any advice or examples? I'm new to Unity3D by the way so I'd appreciate a basic overview of how it works before the "scientific" language.

This is what currently happens when I look up or down and move left/right:

What I want to happen wherever I look up/down or not at all:

My current code:

using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour
{

    public float rotationspeed = 6f;

    private float x, y = 0;

    void Update()
    {
        x += Input.GetAxis("Mouse X") * rotationspeed;
        y += -Input.GetAxis("Mouse Y") * rotationspeed;

        transform.eulerAngles = new Vector3(y, x);
    }

}

Inspector:


texts:
I'm new to OpenGL. I'm studying OpenGL 2.1 and I'm trying to make a little program to test the GL_SPOT_CUTOFF property, but when I set a value between 0.0-90.0, the light doesn't work and everything is dark.

The code:

void lightInit(void) {

    GLfloat light0Position[] = {0.0,0.0,2.0,1.0};
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);
    glLightfv(GL_LIGHT0, GL_POSITION, light0Position);
}

void reshapeFunc(int w, int h) {

    glViewport(0, 0, (GLsizei) w, (GLsizei) h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    if (w <= h)
        glOrtho(-4, 4, -4*(GLfloat)h/(GLfloat)w, 4*(GLfloat)h/(GLfloat)w, -4.0, 4.0);
    else
        glOrtho(-4*(GLfloat)w/(GLfloat)h,4*(GLfloat)w/(GLfloat)h, -4, 4, -4, 4.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt(0,0,0,0,0,-1,0,1,0);

}

void displayFunc(void) {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // center sphere
    glutSolidSphere(1, 100,100);

    // right sphere
    glPushMatrix();
        glTranslatef(3,0,0);
        glutSolidSphere(1, 100,100);
    glPopMatrix();

    // left sphere
    glPushMatrix();
        glTranslatef(-3,0,0);
        glutSolidSphere(1, 100,100);
    glPopMatrix();

    glutSwapBuffers();

}

void keyboardFunc(unsigned char key, int x, int y) {

    if (key==27) {
        exit(EXIT_SUCCESS);
    }

}

int main(int argc, char** argv) {

    //freeglut init and windows creation
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(600, 500);
    glutInitWindowPosition(300, 100);
    glutCreateWindow("OpenGL");

    //glew init and errors check
    GLenum err = glewInit();
    if (GLEW_OK != err) {
      fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
      return 1;
    }
    fprintf(stdout, "---GLEW %s---\n\n", glewGetString(GLEW_VERSION));

    //general settings
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_SMOOTH);
    glEnable(GL_DEPTH_TEST);

    //light settings
    lightInit();

    //callback functions
    glutDisplayFunc(displayFunc);
    glutReshapeFunc(reshapeFunc);
    glutKeyboardFunc(keyboardFunc);

    glutMainLoop();

    return 0;

}

This code produces this image:

If I delete glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);, the next image is produced:

Is there some kind of bug ?


texts: Is there a way to limit the size of the D3DPOOL_MANAGED pool?

texts:
I have over 2GB of textures that I need to put in D3D9's D3DPOOL_MANAGED pool.

D3D9 charges the system copy of anything in the D3DPOOL_MANAGED to my process space. I'm working on a 32-bit system so I have less than 1.7GB of available process space.

Is there a way to limit the size of the pool D3D9 stores in my process, that is to tell it to keep anything else it needs to cache on disk?


texts: Why spritebatch.Draw shows blank output?

texts:
In my code below, I think it's correctly done. But idk, the image called by _bg is does not shown up. The screen only show White. Weirdly, there is 0 error message when I run it.

(The RenderTarget2D is for default-ing my view into landscape mode)

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GameName2
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager _graphics;
        SpriteBatch _spriteBatch;
        Texture2D _bg;

        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            _bg = Content.Load<Texture2D>(@"background");
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            // TODO: Add your drawing code here
            _spriteBatch.Begin();
            _spriteBatch.Draw(_bg,
                new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
                null,
                Color.White,
                0,
                Vector2.Zero,
                SpriteEffects.None,
                0);
            _spriteBatch.End();

            base.Draw(gameTime);

        }
    }
}

I use xnb file. And I put it in Content folder in the project. I've set 'Content' and 'Copy if newer' to the file property.

This is the .png file I use before converted into xnb:

Or maybe the problem is in my .png file?

Any idea?


texts: How many leaderboards can I have in Android via Google Play?

texts:
Question is simple. I have one game with multiple levels(say around 90) distributed amongts different amongst  different worlds.
Am I reading this right and it means I can only have 70 individual leaderboards or is there an alternative (grouping levels/worlds, api, etc)?

Just to be clear, additional information is:

I want to implement level based score, that is one leaderboard for each level (so players can see their score on a level by level basis), one leaderboard for each world, and one leaderboard for the whole game.

Thanks in advance.


texts: How can I get the front buffer into a texture on the GPU?

texts:
I'm attempting to write a small screen capture utility that writes captured video to disk.

First, I get the front buffer surface.  I've written a shader that takes this surface and through render to texture, converts it to a YUY2 format frame.  The format change is required so that I can pass the frames off to an encoder.

I'm using DirectX 9 to acquire the frontbuffer.  There are a couple of ways I know of to get at the front buffer:

GetRenderTargetData()

GetFrontBufferData()

The MSDN page on both of these API calls state that the data is copied from device memory to system memory.  I'd like to copy the front buffer surface directly to another graphics memory surface, as I have other manipulations to perform on the acquired surface before returning it to system memory.

I'm creating a D3DUSAGE_DYNAMIC texture (gfx mem texture) and calling GetFrontBufferData() to write the front buffer to my textures surface0.  Is this valid?  Will the operation remain in gfx memory, or will it need to move to system memory and then back to graphics memory?  If this is the case, is what I'm trying to achieve possible?

EDIT
I've been acquiring the front buffer as below, simply because its a convenient way to get a surface populated:

hr = Dx9Mgr::Ref().D3DDev()->GetFrontBufferData( 0, m_spCaptureSurface );

OTOH, GetBackBuffer() allocates a new surface (I want to reuse one over and over), so I just went with GetFrontBufferData().

GetRenderTargetData() requires that the destination surface be created in system memory rather than in gfx memory (e.g. uses D3DPOOL_SYSTEMMEM ), so I ruled this out.  Maybe I should reconsider?


texts:
I'm new to unity and started learning for 1 week.

But when I add a Sprite and run the game (or check the camera view) I can't see it.

Check this GIF.
https://i.gyazo.com/a54e69096bbd4ef629dcf82b7f90124d.gif

or MP4
https://i.gyazo.com/a54e69096bbd4ef629dcf82b7f90124d.mp4


texts: Coverting byte[] from stereo to mono produces crackling in OpenAL

texts:
I'm trying to convert a Stereo byte[] to mono byte[]

Here is my code :

    private byte[] ToMono(byte[] data)
    {
        byte[] newData = new byte[data.Length / 2];

        for(int i = 0; i < data.Length / 4; ++i)
        {
            int HI = 1; int LO = 0;
            int left = (data[i * 4 + HI] << 8) | (data[i * 4 + LO] & 0xff);
            int right = (data[i * 4 + 2 + HI] << 8) | (data[i * 4 + 2 + LO] & 0xff);
            int avg = ((right + left) / 2);

            newData[i * 2 + HI] = (byte)((avg >> 8) & 0xff);
            newData[i * 2 + LO] = (byte)((avg & 0xff));
        }
        return newData;
    }

It converts to mono alright, but It produces crackling in OpenAL.

It seems that if I compile with "int avg = left;" The crackling stops. But I wanted to mix down both channels.

What is wrong with my code? How can take out the crackling?


texts:
I've recently picked up monogame and am working on a simple top down game to get me started and learn the basics.
I've got the movement and the rotation to follow the mouse sorted out but I'm stuck with the collisions.
What I want to know, basically, are two things:

What would be the best way to handle collisions? I know that Rectangle.Intersects(Rectangle1, Rectangle2) returns the overlapping rectangle, but, as the movement in top down is on x/y axis I'd like to know where the collision is happening so I can create kind of "wall sliding" where the player doesn't get stuck at the wall.
Is checking the players x/y coordinates against solid objects coordinates, then throw the player to his previous position if he enters the bounds of a solid object really the best approach? What would you suggest?
What would be the best way to apply collisions to all of the solids, npc's etc.? I'm currently thinking of creating a gameObject class that all of the objects will inherit from and just handle the collisions there.

Thanks for reading and hope that someone can give me some tips.


texts: How do I play an audio clip repeatedly, controlled by time?

texts:
I have a gun firing sound audio clip and I want this to be played repeatedly while the mouse left button is pressed, like a machine gun where there is automatic firing.
If I do something like:
void Update()
    {
        if (gunScript.gotGun)
        {
            var mouse = Mouse.current;
            var gamepad = Gamepad.current;

            if (mouse != null)
            {
                if (mouse.leftButton.isPressed)
                {
                    gunFireSound.Play();
                }
            }
        }

    }

It plays extremely rapidly as that's how the code gets executed very fast. How do I add a small delay or is there a better way to achieve this?
I also thought of an alternative but it doesn't play it fast enough. (the alternative was an if statement to check if it is finished playing, and play it again)
Thanks in advance. :)


texts: Is it possible to make isometric game of 200 * 200 tiles per map in Unity?

texts:
We made an isometric game in AndEngine. Now we want to convert this game into Unity. I am searching for tiles map support/plugin in Unity. I come across a plugin called Map and nav http://forum.unity3d.com/threads/138355-Tile-Based-Map-amp-Nav . but the problem is it only support 50*50 tiles per map. My map is 200 * 200 tiles. I want to know is there any plugin or way to acheive 200 * 200 tiles per map in Unity ?

Thanks


texts: How to Reciprocally draw on a 3D mesh and 2D UI Image in Unity?

texts:
My question is a bit involved so I'm going to split it into parts and attach a picture.

1) In Unity I'd like to be able to draw a line on a 3D worldspace mesh with the mouse.

2) As I'm drawing on the 3D worldspace mesh, I need to have a 2D UI Image component that represents the same 3D worldspace mesh surface. The UI Image component needs to show the line drawing update in real-time on the UI.

3) I need to be able to also draw a line on the 2D UI Image component and have the line show up on the 3D worldspace mesh.

Currently, I have implemented part 1 by using raycasting and drawing my line on the world coordinates of the returned raycasthit. This works great.

Now, I'm a little at a loss as how to correctly map the world coordinates of the line to the 2D UI Image component's coordinates. I know if I can figure out how to complete step 2, step 3 would simply be reversing the process for step 2.

Here's a picture visualizing what I'm trying to achieve:


texts: Unity update sizeDelta in OnValidate based on Layout Group computed values

texts:
I'm trying to update the sizeDelta of a RectTransform in OnValidate.  I'm trying to grab the computed values from a Layout Group.
Here's what I've got:
#if UNITY_EDITOR
        void OnValidate()
        {
            UnityEditor.EditorApplication.delayCall += Resize;
        }

        private void Resize()
        {
            if (this == null) return;
            RectTransform parentRect = (RectTransform)gameObject.transform;
            RectTransform textRect = (RectTransform)tabText.transform;
            textRect.sizeDelta = new Vector2(parentRect.rect.height, parentRect.rect.width);
            layoutElement.preferredHeight = parentRect.rect.height;
        }
#endif

At first this seemed to be working, but it only works the first time OnValidate runs.  Subsequence invocations of Resize() sets the sizeDelta to Vector2(0, 0).
I'm wondering what causes this and if there's a way to avoid it.  If I remove the delayCall, the values are correct, but I get warnings:

SendMessage cannot be called during Awake, CheckConsistency, or
OnValidate

I'd like to do this at edit time since there's no need to compute this stuff at runtime.


texts:
Let's say I want to replicate Planeshifting from Legacy of Kain: Soul Reaver in Unity.

There are 2 realms: Spectral realm and Material realm.

The Spectral realm is based on the Material realm, only has the geometry distorted and certain objects fade out/become non-interactive.

In Soul Reaver, it is used as means to go to areas where you normally wouldn't be able to in Material (distorting geometry), to use other powers (such as going through grates).

My question is: Is it even possible at all to implement this in Unity 3D? (I would need the Scene(level) or the objects to have 2 states somehow that I could switch beetween/distort to real-time.)


texts: Cursor position to a 3D ray using angles

texts:
I've been stuck for a month trying to get gluUnProject working. After my attempts to use gluUnProject failed (as well as attempts to implement gluUnProject functionality manually) I implemented method to get ray using angles.

 float RadToDeg = 180.0f / (float)M_PI; // conversion coefficient to degree
 float DegToRad = 1 / RadToDeg; // conversion coefficient to radians

 float DeltaX = tan(fovy/2 * DegToRad) * 2 * (Width / 2 - winX) * zNear / Height;
 float DeltaY = tan(fovy/2 * DegToRad) * 2 * (Height / 2 - winY) * zNear / Height;
 float AngleX = atan(DeltaX / zNear) * RadToDeg;
 float AngleY = atan(DeltaY / zNear) * RadToDeg;

 float DeltaXY = sqrt(DeltaX*DeltaX + DeltaY*DeltaY);
 float AngleXY = atan(DeltaXY / zNear) * RadToDeg;
 float AxisAngle = atan(DeltaX / DeltaY) * RadToDeg;
 vec3 RotationAxis = rotate(Camera->X, AxisAngle, Camera->Z);
 if (DeltaY < 0) { RotationAxis = -RotationAxis; }

 vec3 ray = rotate(-(Camera->Z), AngleXY, RotationAxis); //getting ray direction
 ray = vec3(ray.x * scale, ray.y * scale, ray.z * scale); //scale ray if needed

 vec3 RayEndPoint = Camera->Position + ray;

The main idea behind my method is to rotate ray pointing perpendicularly from the middle of the screen (like in first person shooters) to position where you clicked.

Necessary values are fovy angle (field of view in vertical direction), zNear (distance from Camera to near plane) and Camera Transformation Matrix(Camera->X, Camera->Y, Camera->Z, Camera->Position - 1st, 2nd, 3rd and 4th columns). Difference between Camera Transformation Matrix and View Matrix here.

Besides we need some method rotate(vec3 vector,float angle,vec3 axis) that will rotate any vector at any angle around any arbitrary axis.
Explanation how it works will consume too many lines (check photo of my calculations).

Q: Is any easier or better way to do it? Any information or links welcomed.


texts: In Unity3D, what is the relation between inertiaTensor and inertiaTensorRotation?

texts:
In unity3d there are two properties on rigidbody that correspond to the moment of inertia tensor.

One of them is: rigidbody.inertiaTensor, which I know is the diagonal of the inertia tensor,
The other is rigidody.inertiaTensorRotation, which I don't quite understand. I have, though, created a rigidbody in such a way that I get it to be other number than Quatenion.identity, but I still don't see the connection.

Can I describe the products of inertia tensor with the rotation or ... what is the relation between them and where would I require them?


texts: Pitch/Yaw in circle causes undesired Tilt

texts:
I've made my own Camera object, with a forward vector as well as a up vector. I happen to be programming in Android using OpenGL ES 2.0 but I think this question is relevant to all frameworks, it seems to be some math issue I'm not understanding.

Here's a gif of my Pitch/Yaw working correctly:

Here's a gif of Pitch/Yaw in a circle, causing the square to rotate, because the camera is tilting (the up vector becomes negative as I continue).

Here's pseudocode for my pan/yaw functions:

function pitch(amount) {
    if (amount == 0) return;
    forward = normalize(forward + up * amount);

    // Now fix the incorrect up vector
    right = cross(forward, up);
    up = normalize(cross(right, forward));
}

function yaw(amount) {
    if (amount == 0) return;

    right = cross(forward, up);
    forward = normalize(forward + right * amount);
}

I get the same issue if I use Vector rotations instead of Vector Addition (amount is an angle and I use a Rotation Matrix in the X or Y axis)

Pitch: forward = normalize(rotated(forward, angle, Vector3(1, 0, 0)));
Yaw: forward = normalize(rotated(forward, angle, Vector3(0, 1, 0)));

Why is this happening? Is there a way to stop it?

EDIT: I followed the instructions at Why is the camera tilting around the z axis when I only specified x and y? to pitch using the local X axis and yaw using the world Y axis, same result.

Here's the new pseudocode:

function pitch(angle) {
    if (angle == 0) return;

    right = cross(forward, up);
    forward = normalized(rotated(forward, angle, right));

    // Fix the now incorrect up vector
    up = normalized(cross(right, forward));
}

function yaw(angle) {
    if (angle == 0) return;

    forward = normalized(rotated(forward, angle, Vector3(0, 1, 0)));
}

You can see all the code at https://github.com/repwolfe/paper-escaper-android/tree/master/app/src/main/java/com/studioussoftware/paperescaper


texts:
I have a hero character with jumping physics that I am trying to figure out the collision detection for. Right now, the problem that I am running into is as soon as the character hits the floor (while I'm pressing left on the left side of the screen) the rect that it recognizes that it is colliding with is the ground. Which is to be expected.
However, based on the checks that I have,
for sprite in self.group.sprites():
        wall_collide = sprite.feet.collidelist(self.walls)
        if wall_collide > -1:
            print wall_collide
            if self.col_ground(sprite, wall_collide):
                self.hero.jumping = False
                sprite.move_back_y(dt)
            if self.col_left(sprite, wall_collide):
                sprite.move_back_x(dt)
            if self.col_right(sprite, wall_collide):
                sprite.move_back_x(dt)
            print ""

since the character is colliding with the ground, the check to see if the character's rect is inside the colliding rect fails for 2 reasons:
1: The current collision rect is the ground which the character is above, so the test fails
2: Because of #1, the character will keep moving left until it realizes it's colliding with the left side, at which point it will have already gone too far into the wall.
What's the best collision solution?
Note: the character starts to the right of the left wall, on the ground but isn't colliding with the ground since the start position is right above it. Also, I realize that my code is a bit jumbled and I'm not taking care of every sprite in the group. I'll fix that once I have this fixed.
I can provide more code/pictures if necessary
Edit:
More code
def col_ground(self, sprite, wall):
    if self.walls[wall].collidepoint(sprite.feet.midbottom):
        return True
    return False

def col_left(self, sprite, wall):
    if self.walls[wall].collidepoint(sprite.feet.midleft):
        return True
    return False
def col_right(self, sprite, wall):
    if self.walls[wall].collidepoint(sprite.feet.midright):
    return True
return False


texts: How can I tint a Texture2D with a gradient?

texts:
I am working on a lighting system for my game. Instead of lighting each tile completely with only one color, I want to create a gradient on that tile so to make the lighting look more dynamic and nicer.

I am using C# and Monogame (DirectX). Each tile is drawn as a Texture2D with this call:

spriteBatch.Draw(
    Block.getBlockByID(blockID).getTexture(side),
    new Rectangle(x * 28 - offx, y * 28 - offy, 28, 28),
    color
);

The first parameter gets the texture to use and the second one places the texture down. The third one is a pre-calculated Color which shades the texture that color. How can I replace that Color with a gradient?


texts: Ideas/suggestions to implement an item combination system

texts:
I'm designing a game where there is a relatively small set of items. A single player holds an inventory of item slots. Each item slot contains a single item. The inventory allows you to use the item directly, move item around the slots (to organize), equip the item (weapon), and lastly, to combine compatible items together.

I've come up with the diagram below:

Where I'm having trouble is combining. To simplify the game, the game will only do Health+Health, Ammo+Ammo, Weapon+Ammo, Prop+Prop.

Where should I check if the above is permitted? Should Inventory check, or should I delegate the checking to the items themselves?

If I have a green health item and a red health item, it would double the strength of the green potion (increases HP) due to the red health item. But what if the player tries to do: G+G+G+G+G or G+R+R?

I can see that with this design, I run into the problem of having a health item as an (subtype).

For Props, they're simply items used in the game, like keys, cranks, etc. Sometimes two props can be combined as one.

All combinations are designed. As in, the player wouldn't come up with a unique item combination.

Edit 1: The example, with health items, G+G+G+G+G implies that there's a limit as to how many green health items can be combined together. For example, the green health item has a HealthItem.health_sum=.40 (40% of your HP). After the third combination, it becomes meaningless.


texts: Why are my triangles not being drawn in the color I define?

texts:
I render a simple mash structure with Tao (don't think this is relevant) using DisplayList.

Following code appears between

int displayList = Gl.glGenLists(1);
Gl.glNewList(displayList, Gl.GL_COMPILE);

and

Gl.glEndList();

Simplified version of the code, with removed unrelevant parts:

Gl.glBegin(Gl.GL_TRIANGLES);

for (int i = 0; i < triangles.Count; i++)
{
    var triangle = triangles[i];

    bool ok = false;
    var normal = triangle.GetNormal(out ok); //get normal of TRIANGLE

  //this method just retrives correct color information here
    var visualData = GetVisualData(visual,
                      visual.RenderSettings, triangle,null, false);

    //Set the color for the vertex here. Color is always the same in THIS case
    Gl.glColor4f(m_colors[visualData.color.R],
                     m_colors[visualData.color.G],
                             m_colors[visualData.color.B],
                                 visualData.transparency);

    //for every vertex in triangle
    for (int vtx = 0; vtx < triangle.Vertices.Length; vtx++)
    {
         var v = triangles[i].Vertices[vtx];
         Vertex3 v3 = v.Coord;
         Gl.glVertex3d(v3.x, v3.y, v3.z); //set vertex
         Gl.glNormal3d(normal.x, normal.y, normal.z);  //set normal

    }

}

Gl.glEnd();

Accoring to documentation if I set the same color for all 3 vertices of the triangle it must have the solid color. But what I get is:

As you see the colors are not uniform across different triangles, but I'm pretty sure that in this loop the color is not changed, it remains static (I even tried to set constant int values as color , but  result is always the same)

Q:

What can be possible reason of this rendering behaviour?


texts:
I'm planning on my game using multiple backgrounds so I'm trying to use spritefonts to draw the text. Every time I load my spritefont I get a error.

Line1 = content.Load<SpriteFont>("Courier New");
Line2 = content.Load<SpriteFont>("Courier New");

This is the error I get.

Error loading "Courier New". File not found.

Although this was the font listed on the official microsoft website http://msdn.microsoft.com/en-us/library/bb447673.aspx.


texts:
are there any light 3d iphone libraries that must have:

Physics ( ragdoll physics )
3D scene graph
Advanced lighting (lightmapping and stuff)
Sound engine
Ability to import 3D model from blender, 3d studio max, etc.

it should preferably be mature and have no bugs.
i have seen cocos3d but many say it is riddled with bugs.


texts: Synchronizing "token" between players(multiplayer)

texts:
I am implementing the multiplayer(client-server architecture) of a game, and I came to doubt about entities common to players.

I understand how to share information such as the position of the players among themselves. However I am caught up in the logic of how to do for the common entities between them.

Imagine: Two players and a chicken, how would you share the position of the chicken between them? because it needs to move, and can not move in different places in the two clients, the two clients should see the chicken in the local place, but if I send the position of the chicken of one client, and also the other, there may be conflicts.

What should I do. Choose one of the clients to be the "master" who will send the chicken position to the other players? How do they handle this in online games?

I am thinking of doing the following:

I can not imagine the calculations being done on the server working properly, I will use the example of the hens, my hens would have an AI maybe too complex to stay on the server. I thought the following, one of the clients of the update area, as it is a big map, the clients are receiving updates being in chunks of the map, then one of the clients would be the master (the first one that entered the channel) , the others would just listen to it, the "master" client would then send to the server the chicken positions/states and the server would send to all the clients enrolled in the channel the chicken position/status.

It works similar to a "token" who is at the top of the channel users list is going to deal with the chicken's calculations.

advantages:
- Less work for the server to handle.

Disadvantages:
- Poorly trained players could change the position of the hen and make the game experience unpleasant.

What could you do to avoid this disadvantage?


texts:
Hey all I had a question, I was looking into my game's performance and noticed this in the profiler:

Is there any way to optimize this such as pre-generating tiles so it doesn't have to do it each update :) ?


texts: How to scale a sprite with its center as origin?

texts:
I'm trying to zoom-in a sprite gradually from 0% to 100% (a sprite called SelectionBox), so it zooms from the middle of the sprite, not from the upper-left corner. I'm almost there, but I'm having problems with the sprite origin - it's not positioning it in the spot I told it to.

What's wrong with this code?

SpritePosition_FirstBox = New Vector2(15, 50)
MiddleOrigin = New Vector2(CSng(Texture_SelectionBox.Width / 2), CSng(Texture_SelectionBox.Height / 2))

spriteBatch.Draw(Texture_SelectionBox, SpritePosition_FirstBox, Nothing, Color.White, 0, MiddleOrigin, ScaleValue, SpriteEffects.None, 0.94)


texts: How can I fix the face/normal direction of my 3d mesh in blender/UE4?

texts:
So I am playing around with UE4 to make some concept art for a game. I extracted the model I wanted to use from the game's files and imported it into blender. It's a tank with 4 parts: the hull, the suspension, the turret, and the cannon. The suspension and cannon work as intended, but there is something wrong with the way the hull and turret are rendered. Here I have linked 3 photos of what is happening:
http://imgur.com/a/ErpeO

The first screenshot is what the model looks like when rendered in blender (internal and cycles both look like this).

The second screenshot is the model in blender's 3d preview. Looks completely normal.

The third screenshot is what the model looks like in UE4 with textures and normals applied. The outside of the hull and turret meshes are see-through, so only the inside faces on the backside of the mesh are visible.

I have already looked through google and can't find anything to help me. By default the normal direction for the faces (not the vertices) are flipped inside out. Also if I tick "backface culling" blender removes the front faces of the mesh instead of the back faces (should be the other way around). Which means somehow the faces of the 3d mesh are flipped inside out and I need help getting them the way they should be. I have already tried flipping as well as re-calculating the normals (with the "make normals consistent" box ticked) and neither fix the problem. Would really appreciate some help with this. Will upload the model if I have to, but it's not mine so it might be considered copyright infringement.

EDIT: I'm not sure if this matters, but the hull and turret need to be mirrored in blender to match up with the orientation of the cannon/suspension. By defualt they're flipped in the wrong direction. This doesn't seem like a coincidence.


texts:
I'm creating a 2D Tower Defense game and I want it to be isometric. I'm creating it on the XZ plane in Unity(3D mode). I need the map to be based on tiles so I can seperate the monsters' path and the tiles where the player will build the towers on because they will have different scripts attached to 'em. My game will just need one map so I dont need any functionalty like randomizing tiles etc. I've tried using Tiled however, the Tiled2Unity converter doesn't support Isometric maps.

With that said, how do I create a isometric map? Is there any program other than Tiled? Is there any guides or scripts that explain how to create one with different tiles etc, so I can create a path. I've tried looking for something that works but with no results/I dont understand what do do.

This is basicly the look(the angle/path) I want to achieve:


texts: Is there a way to make a game using lwjgl work on android?

texts: I'm working on a platformer and I'd like to make an android version. Do I need to rewrite everything for android, or can I use something to make the lwjgl code work with android?


texts:
I have two points A and B.  I want to perform a smooth deceleration from A stopping at B over time t.  The only thing I managed to do so far was a lerp, which isn't right of course because it's unnatural.  I also tried multiplying the velocity by some factor (0.9 or similar), but then I don't know how to choose the factor such that the end point B is reached (or as near to it as some epsilon value seems reasonable).

Does anyone have something relatively simple that I could use?  I can read C++ and C# code.


texts: libgdx onto existing IOS and Android App, Feasiblity and App Size

texts:
I am an IOS developer, my client has an existing app which they want to add some simple microgames onto. The main requirement is that the app size footprint is as small as possible.

I suggested that Spritekit would give the smallest footprint but they want a cross-platform solution.

My initial reading on libgdx is that is is difficult to implement on IOS.

So before I begin learning libgdx I would like to know whether it is feasible to implement on top of an existing IOS app and whether this is the best solution for a small app size footprint


texts: Scripting Language for Java and its uses?

texts:
So I am going to work on a Java game and recently my friend suggested I use a scripting language to help development go smoother/faster.

so far I used XML as data storage and to make the HUD/UI but he recommended I learn Ruby, Python, Groovy, and/or Lua.

he Strongly recommended Lua for the same thing i use XML for.

basically what my question is :

What are scripting languages, what are they for,, should I use a scripting language, whats the difference between said scripting languages and XML, and which one should I learn and use for my java game?


texts:
I am basically making a game where the whole game is run in the onEnterFrame method. This is causing a delay in my code that makes debugging and testing difficult. Should programming an entire platformer in this method be efficient enough for me to run hundreds of lines of code?

Also, do variables in flash get updated immediately? Are there just lots of threads listening at the same time?

Here is the code...

stage.addEventListener(Event.ENTER_FRAME, onEnter);

function onEnter(e:Event):void
{
//Jumping

if (Yoshi.y > groundBaseLevel)
{
    dy = 0;
    canJump = true;
    onGround = true; //This line is not updated in time
}

if (Key.isDown(Key.UP) && canJump)
{
    dy = -10;
    canJump = false;
    onGround = false; //This line is not updated in time
}
if(!onGround)
{
    dy +=  gravity;
    Yoshi.y +=  dy;
}

//limit screen boundaries

//character movement
if (! Yoshi.hitTestObject(Platform)) //no collision detected
{
    if (Key.isDown(Key.RIGHT))
    {
        speed +=  4;
        speed *=  friction;
        Yoshi.x = Yoshi.x + movementIncrement + speed;
        Yoshi.scaleX = 1;
        Yoshi.gotoAndStop('Walking');

    }
    else if (Key.isDown(Key.LEFT))
    {
        speed -=  4;
        speed *=  friction;
        Yoshi.x = Yoshi.x - movementIncrement + speed;
        Yoshi.scaleX = -1;
        Yoshi.gotoAndStop('Walking');

    }
    else
    {
        speed *=  friction;
        Yoshi.x = Yoshi.x + speed;
        Yoshi.gotoAndStop('Still');
    }

}
else //bounce back collision detected
{
    if(Yoshi.hitTestPoint(Platform.x - Platform.width/2, Platform.y - Platform.height/2, false))
    {
        trace('collision left');
        Yoshi.x -=20;

    }
    if(Yoshi.hitTestPoint(Platform.x, Platform.y - Platform.height/2, false))
    {
        trace('collision top');
        onGround=true;  //This update is not happening in time
        speed = 0;

    }

}
}


texts: How to compress game frame by frame animation to a minimum on disk

texts:
I developing a game like Age of empire (buildings on map) and for every building I have a sprite sheet for its animation. I am using frame by frame animation to animate the building ( not aware of any other method anyways). I am noticing that my resources folder is going extremely large due to the images I am putting in it.

How do games like CoC and Age of Empires keep their apk size under 50 Mg? Am I missing something here when it comes to game development

Thank you

EDIT: More info to the problem I am facing

I have a  LOT of animations drawables objects. I chose this way because it was the quickest and it was yielding the results the I want. Basically every building is an animation drawable in which its xml file refers to 8 drawables (8 images = 8 files). All of them are PNG due to transparency. Since I have over 200 images, the apk size is 120 MB ( And I am not done copying half of the files yet). That's what prompt, there has t o be a way to solve it. Please assist a fellow developer


texts: Where can I find examples of demoscene-like pixel art effects?

texts:
I will keep this simple. The question pretty much sums up what I am looking for. Where are some locations for 2D effects. Specifically ones like those used in old Amiga demos. They do not need to have source code. I am just looking for inspiration to code and replicate some of the effects.

It would be nice to have a list of links to images and examples as opposed to downloading old demos and running them through an emulator.


texts: Mathematics of difficulty acceleration in endless runners

texts: I'm currently working on an endless runner and was wondering about the growth of difficulty in the game. Is the acceleration of difficulty highly specific to games or are there standard growth functions that most endless runners adhere to and fine tune above and beyond that?


texts: How do I use GetComponent on multiple children?

texts:
I'm a beginner and I'm making a game in Unity where I set random colors for four enemies. I made an empty object called "enemies" for me to use it as a folder for the four enemies. I want to get the colors of the enemies and pick randomly one of them for my player.

I wrote this piece of code and I wanted it to store the colors in a list, but whenever I try to print it I find out that it only stores the color of the first child in the "enemies" hierarchy. How do I fix this?

enemies = GameObject.Find("enemies");

GameObject[] allenemies = new GameObject[enemies.transform.childCount];
List<Color> colors = new List<Color>();

foreach (Transform child in transform)
{
    allenemies[i] = child.gameObject;
    i++;
}

foreach (GameObject child in allenemies)
{
    thecolor = enemies.GetComponentInChildren<Renderer>().material.color;
    colors.Add(thecolor);
}

finalcolor = Random.Range(0, colors.Count);
//Debug.Log(finalcolor);

mr.material.color = colors[finalcolor];


texts:
My background and gameobjects are 2d sprites not UI images ,I want to know how to make my background scale with screen size and positions of 2d sprits on it don't change after building game (webGl) like scale canvas with screen size and anchor points in UI elements .

Before building the game

After building


texts:
I am looking to implement with the Microsoft Windows Live game lobby. Since Microsoft has deprecated XNA, I am wondering if it is still possible to interact with the game lobby they provided in XNA (assuming it is not deprecated as well?).

I am doing this for an engine written in C++

In other words, I am wondering if Microsoft is still offering a game lobby system for developers (for indie developers that is). I am trying to track down the documentation for a possible replacement but I can only find resources for XNA.

If not, are there any good, possibly free alternatives? I have no problem writing my own lobby service but I would rather save the time with an already existing solution.


texts: Cannot define Public Transform Target On Unity C#

texts:
Getting UnityError Saying

  "UnassignedReferenceException: The variable target of Movement_Script has not been assigned

Which is line 5 "public Transform target"

I've tried a lot of things... I can't define it.

using UnityEngine;
using System.Collections;

public class Movement_Script : MonoBehaviour {
  public Transform target;
  public float speed = 1;

  void Update () {

    if(Input.GetKeyDown("up"))
    {
      float step = speed * Time.deltaTime;
      transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }
    if(Input.GetKeyDown("right"))
    {
      float step = speed * Time.deltaTime * 10;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
        transform.Rotate(Time.deltaTime,0 ,-90);
    }
  }
}


texts:
I near completion of implementing mymultiplayer game (in WPF/.NET). I want to exploit the game commercially. To do so, I compiled a list of requirements:

.NET/WPF
Game server (multiplayer)
Data server (website/ingame info/widgets/etc)
Website (rules/docs/download)
Forum
Rating system (chess-like, but for 4 players)
OSS is a big pro (or ability to move to OSS in future)

What options do I have to create a platform for hosting the game? Obviously, I can create everything myself, which has advantages and disadvantages. Do you have any experience utilizing exisiting services offering (part or complete) above requirements?


texts: Farseer Physics EndContact events don't fire for all registered delegates

texts:
Here's my situation:

I have several objects that contain a body and a fixture. They are set to sensor = true;

atmosphere = BodyFactory.CreateCircle(world, atmosphereRadius / Level.METER_IN_PIXELS, 1f, new Vector2(pos.X, pos.Y));
atmosphere.IsSensor = true;

//JointFactory.CreateWeldJoint(world, this.getBody(), atmosphere, getBody().LocalCenter, atmosphere.LocalCenter);

this.registerBeginContact(new BeginContactDelegate(this.OnBeginContact));
this.registerEndContact(new EndContactDelegate(this.OnEndContact));

I commented out the join part because it didn't seem to make a difference either way. When the object we control goes enters any of these bodies, the even its fired properly. However, when the player object leaves the sensor field, it doesn't fire the OnEndContact method, EXCEPT if it was the last object that I call

this.registerEndContact(new EndContactDelegate(this.OnEndContact));

When my OnEndContact method is called by the EndContact event in ContactManager, it is called for ALL the delegates I registered, including the ones that are tied to the objects that are not getting these events to fire. The OnBeginContact delegates work perfectly, firing for every object, but the EndContact event does not.

Does anyone have any idea why this is happening or is this a bug in Farseer?

for reference my register methods look like this

public void registerBeginContact(BeginContactDelegate action)
{
    getLevel().getWorld().ContactManager.BeginContact += action;
}

public void registerEndContact(EndContactDelegate action)
{
    getLevel().getWorld().ContactManager.EndContact += action;
}

Thanks in advance.

this is also posted on the farseer code plex page
Faeseer EndContact Discussion


texts: How do I adjust the origin of rotation for a group of sprites?

texts:
I am currently grouping sprites together, then applying a rotation transformation on draw:

private void UpdateMatrix(ref Vector2 origin, float radians)
{
     Vector3 matrixorigin = new Vector3(origin, 0);
     _rotationMatrix = Matrix.CreateTranslation(-matrixorigin) * Matrix.CreateRotationZ(radians) *  Matrix.CreateTranslation(matrixorigin);
}

Where the origin is the Centermost point of my group of sprites.  I apply this transformation to each sprite in the group.

My problem is that when I adjust the point of origin, my entire sprite group will re-position itself on screen.

How could I differentiate the point of rotation used in the transformation, from the position of the sprite group?  Is there a better way of creating this transformation matrix?

EDIT

Here is the relevant part of the Draw() function:

Matrix allTransforms = _rotationMatrix * camera.GetTransformation();

spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, allTransforms);

for (int i = 0; i < _map.AllParts.Count; i++)
{
    for (int j = 0; j < _map.AllParts[0].Count; j++)
    {
       spriteBatch.Draw(_map.AllParts[i][j].Texture, _map.AllParts[i][j].Position, null, Color.White, 0, _map.AllParts[i][j].Origin, 1.0f, SpriteEffects.None, 0f);
    }
}

This all works fine, again, the problem is that when a rotation is set and the point of origin is changed, the sprite group's position is offset on screen.

I am trying to figure out a way to adjust the point of origin without causing a shift in position.

EDIT 2
At this point, I'm looking for workarounds as this is not working.  Does anyone know of a better way to rotate a group of sprites in XNA?  I need a method that will allow me to modify the point of rotation (origin) without affecting the position of the sprite group on screen.

EDIT 3
I think if I was able to reset the screen coordinates to (0,0) at my sprite position, it would essentially allow me to re-position the origin without movement.  I essentially need a way to set the current position/rotation, then start from scratch.  Does anyone know if it is possible to make my sprite the new screen origin?

MOVING ORIGIN WITHOUT A ROTATION:

MOVING ORIGIN WITH A ROTATION (notice how it shifted upwards):


texts: Why doesn't my UE4 character perform an animation?

texts: I have it so that when the character collides with a pushable mesh, it casts to her blueprint and sets ispushing to true, and in her Animation Blueprint, it again casts to her blueprint and sets ispushing? to true. I did this code exactly the same before and it worked, but then the program crashed and I had to redo it.


texts:
So I have a TileSprite class that makes a TileSpriteobject with a collision box in it named bCollisionRect:

public TileSprite(Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
        : base (textureImage, position, frameSize, currentFrame)
{
    bCollisionRect = new Rectangle((int)position.X + collisionOffSet, (int)position.Y + collisionOffSet, frameSize.X - (collisionOffSet * 2), frameSize.Y - (collisionOffSet * 2));
}

But when I try to draw the collision boxes (to test collision detection), it doesn't draw the box. I tried using this:

public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    // This is what I tried:
    spriteBatch.Draw(textureImage, bCollisionRect, Color.White);

    // base.Draw draws the texture (.Draw method from another abstract class)
    base.Draw(gameTime, spriteBatch);
}

I use this line of code in another class to draw my tiles (pure for testing!):

tilename.Draw(gameTime, spriteBatch);


texts:
I'm trying to write a leather material shader. I have a normal map, bump map (grayscaled), specular map, diffuse map, cube maps.

I have done the following

#version 100

precision highp int;
precision highp float;

uniform sampler2D diffuseColorMap;
uniform sampler2D ambientOcclusionMap;
uniform sampler2D normalMap;
uniform sampler2D specularMap;
uniform sampler2D bumpMap;
uniform samplerCube envMap;

varying vec2 texCoord[2];
varying vec3 viewWorld;
uniform float reflectionFactor;
uniform float diffuseFactor;
uniform float opacity;
varying vec3 eyeVector;
varying mat3 world2Tangent;
varying vec3 lightVec;
varying vec3 halfVec;
varying vec3 eyeVec;

void main()
{
    vec3 normal = 2.0 * texture2D (normalMap, texCoord[0]).rgb - 1.0;
    normal = normalize (normal);

    // compute diffuse lighting
    float lamberFactor= max (dot (vec3(0.0,0.0,1.0), normal), 0.1) ;

    vec3 bumpNormal = texture2D(bumpMap, texCoord[0]).rgb;

    vec3 normalWorld = normalize(world2Tangent * bumpNormal);
    vec3 refDir = viewWorld - 2.0 * dot(viewWorld,normalWorld) * normalWorld;

    vec4 diffuseMaterial = texture2D (diffuseColorMap, texCoord[0]);
    vec4 diffuseLight  =  vec4(1.0,1.0,1.0,1.0);

    // In doom3, specular value comes from a texture
    vec4 specularMaterial =  texture2D (specularMap, texCoord[0])  ;
    vec4 specularLight = vec4(1.0,1.0,1.0,1.0);
    float shininess = pow (max (dot (halfVec, normal), 0.0), 2.0)  ;
    vec4 reflection = textureCube(envMap, refDir);

    gl_FragColor=diffuseMaterial * diffuseLight * lamberFactor ;
    gl_FragColor+=specularMaterial * specularLight * shininess ;
    gl_FragColor+= reflection*0.3;
 }

The result is shown:

My question is how would I use the bump map (Grayscale) to the result of the reflection or what's wrong in my shader ?


texts: Best way to create a 2D right-triangle grid

texts:
I would like to create a 2D right triangle grid for a game I am working on. Currently I am creating creating a 2D square grid, and each square contains 2 triangles.

I am wondering, is there a way to create and manage a right-triangle grid without having to contain 2 triangles in each square?


texts: Why does this work in the fragment shader but not in the vertex shader?

texts:
I'm doing some model view and projection transforms in the vertex shader and I want to determine whether the current vertex will end up on the viewport or not.

After searching a bit I found that after the projection transform the coordinates have not been "normalized". So the criteria for a vertex (after the transforms) to appear in the final viewport is the following:

$$-w<x<w$$  $$-w<y<w$$ $$0<z<w$$

where w is the 4th coordinate of the vertex after the transforms

Performing this check I had a great amount of vertices passing the test without being in the viewport and this caused many sorts of problems in whatever I was trying to implement.

However, passing the vertices in their local coordinates to the fragment shader and then doing the exact same process with the transforms and the tests everything worked out fine.

Why?


texts: Dual Contouring - what is it and how to use it?

texts:
I'm having trouble understanding Dual Contouring yet and I need some explanations from someone who has first hand experience.

I searched all I could before writing this question. I've already read:

https://upvoid.com/devblog/2013/05/terrain-engine-part-1-dual-contouring/
http://ngildea.blogspot.com.br/2014/11/implementing-dual-contouring.html

And I'm currently working through:

http://www.frankpetterson.com/publications/dualcontour/dualcontour.pdf
http://ngildea.blogspot.com.br/2015/03/engine-overview.html
http://www.oocities.org/tzukkers/isosurf/isosurfaces.html

I'm not used to all the calculus and math and the information doesn't get into my brain. I really need some clarification, or a tutorial, please.

I'm creating a 3D game with destructible map in Unity 5. I implemented a Minecraft-like voxel system. But how does Dual Contouring work (and how do I implement it in C#)? I don't want to reinvent the wheel, I want to USE it, but if I can't find a ready-made solution in Unity then I need a grounding in how this algorithm works so I can implement it myself.

Not solutions:

Can someone explain dual contouring? is not a duplicate... It's not for me! That question is too straight to the result as the person already mostly understands the proccess. I need help understanding the roles of each function and math components, like the QEF and density.

Also, I looked into Marching Cubes but that won't work for me as I read that it doesn't allow having cubic parts of the mesh in the middle of the smooth ones, and I will use "blocks" in some parts.