# Question
Title: Trying to move the snake smoothly in a 2D game
```
import pygame
from sys import exit
import random

pygame.init()

#Variables for the snake
playerx=580
playery=400
width=10
height=10
white=(255,255,255)
growing= False

#variabels for the ball
ball_width=110
ball_height=500

clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    #Screen Details
    screen=pygame.display.set_mode((1200,800))
    ball=pygame.draw.circle(screen,white,(ball_width,ball_height),3)
    pygame.draw.rect(screen,(255,0,0),(10,0,1160,800),1)
    snake=pygame.draw.rect(screen,white,(playerx,playery,width,height),0)
    pygame.display.set_caption("Snake Game")

    #Keyboard input
    key_pressed=pygame.key.get_pressed()

    if key_pressed[pygame.K_UP]:
        playery-=1
    if key_pressed[pygame.K_DOWN]:
        playery+=1
    if key_pressed[pygame.K_LEFT]:
        playerx-=1
    if key_pressed[pygame.K_RIGHT]:
        playerx+=1

    #Limiting the snake in the box on x size
    if playerx >1160:
        pygame.quit()
    if playerx < 0:
        pygame.quit()

    #Limiting the snake in box on y size
    if playery >800:
        pygame.quit()
    if playery<0:
        pygame.quit()

    #Colliding with the ball
    if snake.colliderect(ball):
        width+=5
        ball_width=random.choice(range(0,1160))
        ball_height=random.choice(range(0,700))

    pygame.display.update()
    clock.tick(90)

```

'Hello ! I wrote this code to create a snake game. For now it is not finished yet . The biggest problem is that I dont know how to move the snake smoothly and by that I mean to move the snake just by 1 block . Now when I move the snake it moves with the whole body . '

# Answer
The "traditional" snake game is grid-based. Basically, maintain a list of body positions. Add a position node from the head when moving, delete a node from the tail, and not delete when the snake grows.

Anyway, to achieve "smooth" movement, there must be a list of body positions:

```
player=[(580,400)]

```

To make the growth noticeable, set a minimum moving distance:

```
step_len = 5
...
isMoved = True
if key_pressed[pygame.K_UP]:
    playery-=step_len
elif key_pressed[pygame.K_DOWN]:
    playery+=step_len
elif key_pressed[pygame.K_LEFT]:
    playerx-=step_len
elif key_pressed[pygame.K_RIGHT]:
    playerx+=step_len
else:
    isMoved = False

```

And update the snake body when moving:

```
if isMoved:
    player.insert(0,(playerx,playery))
    #Colliding with the ball
    if snake.colliderect(ball):
        # roll the ball
    else:
        player.pop(-1)

```

Full code:

```
import pygame
from sys import exit
import random

pygame.init()

#Variables for the snake
step_len = 5
player=[(580,400)]
width=10
height=10
white=(255,255,255)
growing= False

#variabels for the ball
ball_width=110
ball_height=500

clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    #Screen Details
    screen=pygame.display.set_mode((1200,800))
    ball=pygame.draw.circle(screen,white,(ball_width,ball_height),3)
    pygame.draw.rect(screen,(255,0,0),(10,0,1160,800),1)
    snake = None
    for i in range(len(player)):
        node = pygame.draw.rect(screen,white,(player[i][0],player[i][1],width,height),0)
        if i ==0:
            snake = node
    pygame.display.set_caption("Snake Game")

    #Keyboard input
    key_pressed=pygame.key.get_pressed()

    playerx,playery = player[0][0],player[0][1]
    isMoved = True
    if key_pressed[pygame.K_UP]:
        playery-=step_len
    elif key_pressed[pygame.K_DOWN]:
        playery+=step_len
    elif key_pressed[pygame.K_LEFT]:
        playerx-=step_len
    elif key_pressed[pygame.K_RIGHT]:
        playerx+=step_len
    else:
        isMoved = False

    if isMoved:
        #Limiting the snake in the box on x size
        if playerx >1160:
            pygame.quit()
        if playerx < 0:
            pygame.quit()

        #Limiting the snake in box on y size
        if playery >800:
            pygame.quit()
        if playery<0:
            pygame.quit()

        player.insert(0,(playerx,playery))
        #Colliding with the ball
        if snake.colliderect(ball):
            ball_width=random.choice(range(0,1160))
            ball_height=random.choice(range(0,700))
        else:
            player.pop(-1)

    pygame.display.update()
    clock.tick(50)

```
> 2 votes

---
Tags: 2d, snake
---


title: Lowest quality PC development?

text:
# Question
Title: Lowest quality PC development?
Okay, so I have a little bit of experience with Unreal Engine and Unity, but I am much more of a backend guy and C# is my language of choice. The difficulty I am having at the moment is that while it feels like there are 1000's of tutorials on how to render at the highest possible quality in these software's (or how to get the best balance on mid settings), I can't seem to find any videos on how to achieve the **lowest quality render**. The user interface is frustrating me because I am used to being able to start with a blank(ish) slate and then coding up (the last time I made a game for publication I was using XNA in VS10, passing render calls in code etc).

Could anyone give me a helping hand/pointer towards what the optimal lowest quality settings are for either software for a 'blank slate'? Ideally, for whichever of the two has the broadest range of compatibility. Are there any settings which have a much larger overhead for the processor/RAM?

The purpose here, for context, is not to achieve lowest graphical quality - but to achieve broadest legacy support. I want settings that a vampire could run on windows 1874BC if they wanted.

The project is 3D, I am not majorly concerned with having the best textures and lighting, all of my models are optimised very well, I am intending to make a large scale map which streams in. Object position and mechanics are the priority.

I'm not interested in all the bells and whistles (no raytracing etc), I'd just like to be able to render a cube in the middle of a screen with the lowest overhead on the most devices.

A simpler way to phrase my question would probably be: **how do I turn everything off except the absolute essentials?**

Any help here would be greatly appreciated, especially if you have any links to YouTube videos/channels which cover broad-compatibility games in Unity.

# Answer
> 0 votes
I suspect Unity’s Project Tiny might be exactly what you are looking for. It tries to cram the most game into the smallest possible space and power.

https://forum.unity.com/forums/project-tiny.151/

---
Tags: unity, unreal-5
---


# Question
Title: LibGDX Invalid animation during actor rotation
I have a problem with the animation when setting the actor's rotation. Every now and then the server sends an updated actor's rotation position. The client uses interpolation to smoothly update the old position to the new one. Everything works fine until the actor should turn between 180° and -180°. In this case, I see unnatural behavior - the actor does a full lap instead of moving a tiny bit. How to fix it?

Render method:

```
ACTOR.setRotation(ACTOR.getRotation() + (destinationRotation - ACTOR.getRotation()) * 10f * Gdx.graphics.getDeltaTime());

```

"destinationRotation" is a variable containing the updated rotation position.

I attach a picture to illustrate situation.

# Answer
> 0 votes
*Disclaimer: It has been a good while since I've done anything in Java, and that is without considering LibGDX.*

---

We need to make sure we have the shortest way to go from the `current_angle` to the `target_angle`. For that we will implement `wrap`:

```
float wrap(float value, float lower_bound, float upper_bound)
{
    float range = upper_bound - lower_bound;
    return value - (range * Math.floor((value - lower_bound) / range));
}

```

Then we can get our angle offset like this:

```
float half_turn = 180f; // or Math.PI if we were using radians
float current_angle = ACTOR.getRotation();
float target_angle = destinationRotation;
float offset_angle = wrap(target_angle - current_angle, -half_turn, half_turn);

```

It should give us the angle difference, the shortest way.

*I'm sure there are other ways to do this. I don't know if there is a better one for Java.*

---

We want to apply an angular velocity. So we will compute how much we can rotate:

```
float delta = Gdx.graphics.getDeltaTime();  // seconds
float rotation_speed = 10f;                 // angle per second
float angle_delta = rotation_speed * delta; // angle

```

---

Now, notice that our `angle_delta` is always positive. But not our `offset_angle`. So we are going to decompose `offset_angle` into `sign` and `magnitud`:

```
float offset_angle_magnitud = Math.abs(offset_angle);
float offset_angle_sign = Math.signum(offset_angle);

```

So we can limit how much we rotate so we don't overshoot, while preserving the sign:

```
float rotation_angle = Math.min(angle_delta, offset_angle_magnitud) * offset_angle_sign

```

Finally add that to the `current_angle`:

```
ACTOR.setRotation(current_angle + rotation_angle);

```

I don't know if you would need to wrap at the end there (or if `setRotation` handles that already):

```
ACTOR.setRotation(wrap(current_angle + rotation_angle, -half_turn, half_turn));

```

Or perhaps `rotate` works better:

```
ACTOR.rotate(rotation_angle);

```

---

**Addendum**

The above code has the behavior of a sudden start/stop.

In a more conventional situation we would use an acceleration, but that would require to add state (either keep track of time or the current velocity). However, we cannot simply increase velocity with acceleration… Because we also want to decrease velocity and smoothing reach zero.

Thus, we want a solution with variable acceleration. How do we know if we should increase or reduce the acceleration? Intuition dictates that it should be some function of how far we are from the destination. Well, I'll cut the middle man and make the the velocity a function of the angle (this way our approach can remain stateless). This approach requires four parameters:

* We will specify a range of angles (minimum and maximum) over which we will do easing. Which I'll call `min_angle` and `max_angle`.
* Similarly there will be a range of angular velocities (minimum and maximum). Which I'll call `min_rotation_speed` and `max_rotation_speed`.

For practical proposes, the minimum angle and the minimum angular velocity will be zero. Yet, I'll leave the variables in for reference. *Feel free to optimize once you have a solution that behaves the way you want.*

We need to compute the size of the angle range:

```
float angle_range = max_angle - min_angle

```

*I'm assuming that `max_angle > min_angle`, if that is not the case you can swap them. We should have a positive `angle_range`.*

We will only do easing if this `angle_range` is not zero:

```
if (angle_range > 0f)
{
    // …
}

```

Now, we will map the `offset_angle_magnitud` to a value between zero and one which indicates where it is in the `angle_range`:

```
if (angle_range > 0f)
{
    float x = Math.min(
        max(offset_angle_magnitud - min_angle, 0.0) / angle_range,
        1.0
    );
}

```

This should give you zero below `min_angle` and one above `max_angle`, a number in between in the middle.

And now that we have a value between zero and one, we can interpolate:

```
if (angle_range > 0f)
{
    float x = Math.min(
        max(offset_angle_magnitud - min_angle, 0.0) / angle_range,
        1.0
    );
    angle_delta = interpolate(min_rotation_speed, max_rotation_speed, x) * delta;
}

```

*Notice than alternative is to use a `smoothstep` function. But that is just one option, I'll go for something general.*

We can write that `interpolate` in terms of an ease function:

```
float interpolate(float lower_bound, float upper_bound, float weight)
{
    return (upper_bound - lower_bound) * ease(weight) + lower_bound;
}

```

And there are many options for the `ease` function. Be aware that this function controls the velocity as a function of the angle. You can start with simply this:

```
float ease(float x)
{
    return x;
}

```

*The above function would make `interpolate` a linear interpolation (a.k.a `lerp`).*

With that, as the angle to the destination becomes larger, the velocity also becomes larger. Similarly as the angle to destination becomes smaller, the velocity also becomes smaller.

However, my intuition is that your function should have a quadratic behavior. You can try that too:

```
float ease(float x)
{
    return x * x;
}

```

You can find more easing functions searching online. There are some "cheat sheets" such as this one: https://easings.net \- pick, test, choose. *Then - if want - you can inline these functions, and you may find some cancellations in the process.*

---
Tags: java, libgdx
---


# Question
Title: Vibration duration for mobile devices in Unity
I'm used the `Handheld.Vibrate()` method. I know that if you call it several times, you can increase the vibration time, but when it is called once, the vibration lasts about 1 second. But I would like to make an imitation of clicking on the android keyboard. (Vibration ~ 0.2s)

**How to set the duration of the vibration?**

# Answer
You can use this script, which calls the native Android API:

https://gist.github.com/ruzrobert/d98220a3b7f71ccc90403e041967c46b

The author allows commercial use and even adopting the script

The script provides a lot of options, e.g.

```
// vibrating for 500 milliseconds with an amplitude of 50
Vibration.Vibrate(100, 50)

// using predefined effects
VibratePredefined(1)

```

---

iOS doesn't seem to provide any methods for finer control than `Handheld.Vibrate()`.
> 2 votes

# Answer
```
void Start()
{
    StartCoroutine(VibrateDuration());
}

public IEnumerator VibrateDuration()
{
    yield return new WaitForSeconds(2.0f);
    Handheld.Vibrate();
}

```
> -4 votes

---
Tags: unity, c#
---


# Question
Title: Save Resource Usage when Player is inactive
I have a windows standalone player which is running on surface laptop. As you know it works on batteries so i want to add a feature of power save/resource save when the player is inactive? Is there any standard way to do this thing?

**My strategy:** I know that if the player is not doing anything like he is not moving for some times or he he didn't click on screen for a particular time period then turn off the camera component?

# Answer
> 1 votes
This is an unrealistic problem. The player is very unlikely to leave the game running unpaused and walk away from the computer for an extended period while the computer is running on battery. Gamers understand that games use battery power. Also, think about *when* a player is likely to leave their device on battery power. You're most likely to use the battery if you're outdoors, traveling, or in a public place without easy access to outlets (e.g. at school). In any of these circumstances, the user is unlikely to leave his or her device unattended because it could get stolen. In places where it's safe to leave a device unattended, such as at home, the user likely has access to outlets to plug in his or her device.

You should of course **create a pause menu** for when the player needs to leave the game unattended for a short period. While the game is paused, you can do various things to reduce power usage, such as:

* Set `Time.timeScale = 0`
* Temporarily disable components that don't need to run while the game is paused
* Disable your main camera, and enable a camera that uses the Culling Mask to only render the pause menu.

Players who need to step away from the game for an extended period are more likely to minimize (if not quit) the game. In the Player Settings, you can **disable the "Run in Background" option to greatly reduce battery usage while the game is minimized**.

If it's a multiplayer game that can't be paused - well, players shouldn't be leaving the game running unattended while they're in multiplayer, so why optimize for this edge case?

When developing a game, it's best not to let yourself get distracted trying to solve hypothetical problems that are unlikely to come up in the real world. Focus your time on actually developing and publishing your game, not on unnecessary features.

---
Tags: unity, c#
---


# Question
Title: How to implement a directional attacking/blocking system?
I'm working on implementing a directional attacking / blocking system in Unity à la Elder Scrolls: Arena or more recently, Mount & Blade \- where moving the mouse in a certain direction signals a direction of attack. As expected, you will also be able to block in each direction, with each block direction countering the attack coming from the same direction.

I was wondering how to best implement this? Specifically: do I use colliders and actually make attacks physically collide with a potential shield or weapon in that direction? Or do I merely hold an enum with direction state and compare these values when a collision occurs? Any further expanded ideas and suggestions are welcome!

# Answer
There's no single right answer for this. It depends on what works best for your game. However, there are some complications you may not have thought of when using an enum:

Let's imagine two characters A and B are facing each other directly. Character B swings a sword from left to right. Obviously, in this case, Character A should block on his right side (remember, if A and B are facing each other, A's left is B's right and vice-versa).

It gets way more complex and confusing as soon as A and B aren't facing each other directly. Look at this scenario:

Here, character B is attacking character A from A's left side. In this situation, A should have to block left, regardless of whether B is swinging from left-to-right or right-to-left. Clearly, we need extra code to determine the block direction if the attacker is not directly in front of the defender.

With physics/collision based code, you don't have to write code to determine attack/defend directionality, and it's easier to add projectiles (such as arrows). However, the performance cost may be higher, and it's sometimes difficult to troubleshoot and fine-tune issues with attacks getting blocked when they shouldn't, or not getting blocked when they should. You have to remember to watch out for gotchas like a lack of continuous detection (CCD); without CCD, an attack might pass right through a shield without hitting it.

With custom code that doesn't use physics/colliders, it can be easier to debug the code (since you have total control over the logic, and can add breakpoints and logging anywhere), and you don't have to worry about issues like CCD. On the other hand, you have to write all of the code to handle hit detection and attack directionality, and could end up with a mess of edge cases that's difficult to understand. It's also easy to get confused about direction (e.g. if I say "attack right", does that mean swinging a sword from left-to-right or right-to-left?, or forgetting that if A and B are facing each other, A's left is B's right and vice-versa). If you don't know what you're doing, your hit detection code might be much slower than the built-in physics system (how much that matters depends on how many characters are fighting at one time).
> 0 votes

---
Tags: unity, collision-detection, 3d, game-mechanics, combat
---


# Question
Title: Licensing for assets in a game but it is free for commercial use
In my game, there is this music that I use and of course before releasing anything for commercial use, I have to have a license for what I dont create for my game for example ( game engine, music, fonts and etc ) some of them are free to use even for commercial purposes.

**My question is** do I need license for it even though it is free for commercial use? and if there is no license for it at all, what should I do to avoid copyrights and legal issues?

# Answer
Based on your description of "free to use even for commercial purposes", it sounds like it already has a license. In this case, one that indicates you can use it for commercial purposes. Conversely, how do you know it can be used in that manner if there wasn't a license saying so?

Most licenses I'm familiar with persist in the sense that they apply to the work in question after you've used. For instance, if it's already free for commercial use, it typically stays that way - your use can't restrict others from using it. Furthermore, many licenses include some language indicating that they must explicitly accompany the work. So if you're using a piece of music with a free for commercial use license, you often must include a copy of the license either directly in the game (as a start up splash screen or an always accessible credits screen) &/or as an accompanying text file.

However, situations & licenses vary, so as indicated in the comments, you should need to post the actual terms of use for the asset in question to ensure we're talking about the same thing.
> 1 votes

# Answer
You definitely need a license along with the music. Unless it is explicitly public domain, you still need to keep whatever licensing they had on it. If there is no license for it, contact the creator of the song (or asset) about their work and they will normally tell you the copyright license they have on it and whether or not you can use it.
> 0 votes

---
Tags: assets, legal, licensing, commercial, asset-creation
---


title: Game loop c++ implementation

text:
# Question
Title: Game loop c++ implementation
I'm starting to develop some simple 3D game. The basic topic for a start is the *game loop*.

There is a solution:

```
while (true)
{
    while (PeekMessage(&msg,0,0,0,PM_REMOVE)
    {
        // Translate and dispatch message
    }

    if (msg.message == WM_QUIT)
    {
        break;
    }

   // Do update, rendering and all the real game loop stuff

}

```

proposed by *Syntac\_* in this thread.

The above answer revived positive feedback WHILE the solution seems to NOT be valid! When I click on the close ('X') button (or just press ALt+F4) to close the main app window nothing happens - the app is still running! Fast investigation - the problem is that the app receives some extra *WM\_TIMER* message after the *WM\_QUIT* message so the `if (msg.message == WM_QUIT)` is NEVER reached!

# Answer
> 2 votes
The general pattern for a Win32 game loop is:

```
MSG msg = {};
while (WM_QUIT != msg.message)
{
    if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else
    {
        // Tick which is usually one or more Updates + 1 Render
    }
}

```

This ensures you will eventually see the `WM_QUIT` and exit the loop without any message order dependencies. It also makes sure you process all pending application messages *before* proceeding with the next frame Tick to keep it responsive.

Also make sure in your `WndProc` you do:

```
switch(message)
{
case WM_DESTROY:
    PostQuitMessage(0);
    break;
...

```

and a helper like this is useful too for logic-based triggering of exit:

```
void ExitGame() noexcept
{
    PostQuitMessage(0);
}

```

> I suspect another problem here is because you are making heavy use of `WM_TIMER` messages for your game timing, which is really easy to overload the system with requests. It's also 'wall clock' timing which isn't necessarily the right choice for your game timer.

> A better answer is do your own time event detection inside the game loop. See this blog post for details on using StepTimer.h.

See GitHub for an bunch of simple game loops plus Direct3D device & swapchain.

# Answer
> 1 votes
There are other reasons why you might want to quit the game. For example when the player selects "quit to desktop" from the main menu. I would therefore recommend to add a flag variable `quitGame` and set that variable to true when you want to end the game for *any* reason. Then just check that variable in your while-loop:

```
bool quitGame = false;

while (!quitGame)
{
    while (PeekMessage(&msg,0,0,0,PM_REMOVE))
    {
        // Translate and dispatch message
        if (msg.message == WM_QUIT)
        {
            quitGame = true;
        }
    }

    // Do update, rendering and all the real game loop stuff

}

```

---
Tags: c++, game-loop
---


title: Java Netty cannot connect to the server

text:
# Question
Title: Java Netty cannot connect to the server
I am creating a simple 2d multiplayer game supported by the Netty library. The server is located on my local computer. I have a problem: why are some clients unable to connect? I tested on several computers from different places connected to different networks. Virtually always everything works fine. For some reason my friend is unable to connect. What could be the reason? Others connect without any problems. I would like to add that we have the same network operator. The problematic person is the only one who has a different operator. Could it have anything to do with it? I am new to the operation between the server and the client. Why does it work for some and not for others? What are the possible reasons? I would be very grateful for your help.

EDIT:

Server setup:

```
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(new ObjectEncoder());
                            pipeline.addLast(new ServerHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.bind(8080).sync();

            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

```

Client setup:

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(new ObjectEncoder());
                            pipeline.addLast(new ClientHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect("<SERVER IPv4>", 8080).sync();

            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
```

# Answer
> 0 votes
This doesn't seem to be related to game development. (maybe?) Before checking your game code, first make sure that the network connection is working. Based on the information you have, maybe you can do the following checks:

1. Make sure the tool to check network connectivity (ping command) is working. Try ping the server with a device you can connect successfully, if that fails, the firewall may be blocking the pings. Configure the Windows firewall to allow pings (You mentioned CMD so I assume you are using windows system).
2. If all devices can ping successfully, it is a problem with the game code. And If only some devices(your friend's) cannot ping successfully, it is a network problem.
3. For a network problem, better answers can be found on other exchange sites. Here are just some preliminary guesses:

> I tested on several computers from different places connected to different networks.

1. Just in case, How *different* are these places and networks? Maybe they are in the same lan and you are using the lan ip? You can check your public ip here.
    2. Did your network operator provide you with a public ip even? Is it dynamic?
    3. Are either network of yours regulated? Does opening port 8080 require filing in your area?

---
Tags: java, networking
---


title: First triangle not drawn

text:
# Question
Title: First triangle not drawn
I'm trying to simply draw a triangle but for some reason I can't see any.

I made sure that every buffer was bound before use. Added the shader/program error chec. Added some logs using `glDebugMessageCallback` also but had no luck on this, the debug infos weren't relevent.

Does someone has any idea on this ?

Here is the `glfw` context:

```
GLFWwindow* createContext( unsigned int width, unsigned int height, const char* name ) {
  if ( !glfwInit() )
    throw "Couldn't open the window";

  glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
  glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );

  glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, true );
  glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
  glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );

  auto window = glfwCreateWindow( width, height, name, NULL, NULL );
  glfwMakeContextCurrent( window );

  return window;
}

```

Here is the init in main:

```
  auto window = createContext( 1280, 960, "Simple Triangle" );
  if ( !window ) {
    std::cout << "Couldn't open window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwSetErrorCallback( errorCallback );

  glewExperimental = true;
  glewInit();

  glViewport( 0, 0, 1280, 960 );
  glEnable( GL_DEPTH_TEST );
  glDepthFunc( GL_LESS );

  glEnable( GL_DEBUG_OUTPUT );
  glDebugMessageCallback( errorCallback, NULL );

```

Here is how I set up the shaders and the program:

```
  float vertices[] = {
    -0.5f, -0.5f, 0.0f,
     0.5f, -0.5f, 0.0f,
     0.0f,  0.5f, 0.0f
  };

  float color[] = {
    1.0f, 0.0f, 0.0f,
    0.0f, 0.5f, 0.0f,
    0.0f, 0.2f, 0.0f
  };

  GLuint vbo;
  glGenBuffers( 1, &vbo );
  glBindBuffer( GL_ARRAY_BUFFER, vbo );
  glBufferData( GL_ARRAY_BUFFER, sizeof ( vertices ), vertices, GL_STATIC_DRAW );

  GLuint colorVbo;
  glGenBuffers( 1, &colorVbo );
  glBindBuffer( GL_ARRAY_BUFFER, colorVbo );
  glBufferData( GL_ARRAY_BUFFER, sizeof ( color ), color, GL_STATIC_DRAW );

  GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER );
  auto fileContent = IoHelper::readFile( "shaders/simple.vert.glsl" );
  auto source = fileContent.c_str();
  std::cout << "Vertex Shader:\n" << fileContent << std::endl;
  glShaderSource( vertexShader, 1, &source, NULL );
  glCompileShader( vertexShader );
  getShaderCompileError( vertexShader );

  std::cout << "-----------------------------------------" << std::endl;

  GLuint fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
  fileContent = IoHelper::readFile( "shaders/simple.frag.glsl" );
  source = fileContent.c_str();
  std::cout << "Fragment Shader:\n" << fileContent << std::endl;
  glShaderSource( fragmentShader, 1, &source, NULL );
  glCompileShader( fragmentShader );
  getShaderCompileError( fragmentShader );

  GLuint program;
  program = glCreateProgram();
  glAttachShader( program, vertexShader );
  glAttachShader( program, fragmentShader );
  glLinkProgram( program );
  getProgramCompileError( program );

  GLuint vao;
  glGenVertexArrays( 1, &vao );
  glBindVertexArray( vao );

  glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof ( vertices ), NULL );
  glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, sizeof ( vertices ), NULL );
  glEnableVertexAttribArray( 0 );
  glEnableVertexAttribArray( 1 );

```

Here is my main loop:

```
  while ( !glfwWindowShouldClose( window ) ) {
    glClearColor( 0.2f, 0.3f, 0.3f, 1.0f );
    glClear( GL_COLOR_BUFFER_BIT );

    glUseProgram( program );
    glDrawArrays( GL_TRIANGLES, 0, 3 );

    glfwPollEvents();
    glfwSwapBuffers( window );
  }

```

And finally my shaders:

```
Vertex Shader:
#version 430

layout ( location = 0 ) in vec3 iPos;
layout ( location = 1 ) in vec3 iColor;

out vec4 oColor;

void main()
{
    gl_Position = vec4( iPos, 1.0 );
    oColor = vec4( iColor, 1.0 );
}

-----------------------------------------
Fragment Shader:
#version 430

in vec4 oColor;
out vec4 fragColor;

void main()
{
    fragColor = oColor;
}

```

Thank you

# Answer
> 1 votes
With some research and some tries, I finally found where the problem came from.

I tried using

```
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

```

instead of

```
glClear( GL_COLOR_BUFFER_BIT );

```

Does someone have an explanation on this ?

Thanks

# Answer
> 0 votes
have you tried changing the `glDrawArrays( GL_TRIANGLES, 0, 3 );` to `glDrawArrays( GL_TRIANGLES, 0, 9 );`?

# Answer
> 0 votes
As you've already found out in your own comment you have to clear the depth buffer. You've enabled depth testing with GL\_LESS while rendering the same fragment over and over again, so 'new' one's depth is not less than the 'old' one's, thus it is discarded. https://www.khronos.org/opengl/wiki/Depth\_Test#Depth\_test

---
Tags: opengl, c++
---


# Question
Title: In pygame I am trying to add the text as an integer and it keeps crashing, why?
I am trying to convert the string as an integer when I am using the `font.render()` function but it keeps saying different things like *it has to be a unicode or string* and so on. I am trying to display the scoreboard as text and in the right size the score which is getting +1 every time the snake gets the collision with the ball.

```
import pygame
from sys import exit
import random

pygame.init()

#Creating the score font
arial_font=pygame.font.SysFont("arial",20)
text=arial_font.render("Scoreboard", False, (255,0,0),(0,0,0))
#Creating the number score font
arial_font2=pygame.font.SysFont("arial",20)
score=arial_font2.render(scoreline, False, (255,0,0),(0,0,0))

#Score variable
scoreline=0

#Variables for the snake
step_len = 5
player=[(580,400)]
width=10
height=10
white=(255,255,255)
growing= False

#variabels for the ball
ball_width=110
ball_height=500

clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    #Screen Details
    screen=pygame.display.set_mode((1200,800))
    ball=pygame.draw.circle(screen,white,(ball_width,ball_height),3)
    pygame.draw.rect(screen,(255,0,0),(10,0,1160,800),1)
    screen.blit(score,(300,400))
    def score():
        screen.blit(text ,(200,300))

    score()
    snake = None
    for i in range(len(player)):
        node = pygame.draw.rect(screen,white,(player[i][0],player[i][1],width,height),0)
        if i ==0:
            snake = node
    pygame.display.set_caption("Snake Game")

    #Keyboard input
    key_pressed=pygame.key.get_pressed()

    playerx,playery = player[0][0],player[0][1]
    isMoved = True
    if key_pressed[pygame.K_UP]:
        playery-=step_len
    elif key_pressed[pygame.K_DOWN]:
        playery+=step_len
    elif key_pressed[pygame.K_LEFT]:
        playerx-=step_len
    elif key_pressed[pygame.K_RIGHT]:
        playerx+=step_len
    else:
        isMoved = False

    if isMoved:
        #Limiting the snake in the box on x size
        if playerx >1160:
            pygame.quit()
        if playerx < 0:
            pygame.quit()

        #Limiting the snake in box on y size
        if playery >800:
            pygame.quit()
        if playery<0:
            pygame.quit()

        player.insert(0,(playerx,playery))
        #Colliding with the ball
        if snake.colliderect(ball):
            scoreline+=1
            ball_width=random.choice(range(0,1160))
            ball_height=random.choice(range(0,700))

        else:
            player.pop(-1)

    pygame.display.update()
    clock.tick(50)

```

# Answer
> 2 votes
Your code is odd. e.g., in this code, you use a variable `scoreline` without it being initialized first.

```
arial_font2=pygame.font.SysFont("arial",20)
score=arial_font2.render(scoreline, False, (255,0,0),(0,0,0))

```

---

You're defining the `score` variable first as a surface (I think), so it would make sense to eventually use it like that `screen.blit(score,(300,400))`, like you're doing now.

The issue probably comes from the fact that you're overriding what `score` is. It was a surface, but after this code:

```
def score():
    screen.blit(text ,(200,300))

```

it is now a function, and so it can't be rendered.

I suppose this mess comes from the fact that you've been trying a couple of things that your gut told you.

Don't worry, we've all been there.

So I think that instead of what's here:

```
screen.blit(score,(300,400))
def score():
    screen.blit(text ,(200,300))

score()

```

you likely want something like this:

```
screen.blit(score,(300,400))
screen.blit(arial_font2.render(str(scoreline), False, (255,0,0),(0,0,0)),(200,300))

```

The key part here, is that the `render` function expects *text*, not an *integer*. You need to convert the content of `scoreline` to *text* before supplying it to the `render` function, and you do that by using the `str` python function.

I don't have access to pygame for now, but that should help you get started.

---
Tags: pygame, text
---


# Question
Title: How to make a character walk in GameMaker
I am making a game with my friend and I'm sorting out some scripts. When I was writing the script for walking, I got the error message below. What did I do wrong?

Here is my code:

# Answer
When you see an error message like:

> `Variable [variable_name] not set before reading it.`

it means your program is trying to change the value of a variable that doesn't exist. You shall declare a variable in the **Create Event** so that other object scripts can use and manipulate its value thereafter.

More precisely, you are setting the value of the built-in instance variable `x` relative to `-move_speed`. If it were GML Code, it would be equivalent to:

```
x -= move_speed;

```

Unfortunately, it seems that `move_speed` is unknown to the current object. The **Key Press Event** cannot decrease `x` by `move_speed` because it has no idea what `move_speed` is.

You can fix this by adding a **Create Event** to the object and including a **Assign Variable** GML Visual block, in which you define `move_speed` as a new instance variable that can later be referenced in other blocks or scripts.
> 1 votes

---
Tags: game-maker, game-maker-studio-2
---


# Question
Title: DontDestroyOnLoad only works for root GameObjects
I have this simple code, but it does not prevent the object it's attached to from being destroyed on load:

```
 void Start()
{
    DontDestroyOnLoad(gameObject);
    Debug.Log(gameObject.scene.name);
}

```

It also shows this Warning:

> DontDestroyOnLoad only works for root GameObjects or components on root GameObjects.
> UnityEngine.StackTraceUtility:ExtractStackTrace ()
> wfb:Start () (at Assets/Script/wfb.cs:9)

`DontDestroyOnLoad(gameObject);` is on line 9.

# Answer
> 5 votes
Check your Hierarchy to see if the object is the top-level parent or a child of another object.

If the game object is a child, the `DontDestroyOnLoad()` function will not work.

In order to not destroy the game object you need to place it at the root level of the scene, not parented to any other object, so that the game object will persist to the other scene.

The warning is saying that this object is currently a child (or grandchild, etc.) of another root object in the scene.

# Answer
> 0 votes
set this line code before DontDestroyOnLoad you will avoid the error: yourObj.parent = null;

---
Tags: unity, c#
---


# Question
Title: How to structure a loop so that a variable goes from 0 to 20 and then back to 0 again... indefinitely (until an outside variable changes)
I am working in Unity using Visual Scripting - but am looking here for general advice for looping algorithms!

I made a While loop that continues as long as a boolean glowactive is true. It's under a "On Enter State" that has coroutines enabled.

Then the code enters 2 separate For loops, that go from 0 to 20 and back again. (Actually it goes from 0 to 1 in 0.05 increments, but it's the same idea.)

The loop runs as long as glowactive is true... but glowactive isn't changed in the loop. However, it can be changed in other parts of the code. I read though that you should never have a While loop with a condition that doesn't change inside the loop... or you will get an infinite loop. That may well be true, because I am indeed getting an infinite loop!

Any advice on how to properly setup loops to achieve my goal? I basically want to continuously vary the \_GlowPower from 0 to 1.0, by increments of .05. This makes the text glow on and off.

It works for about 2 cycles or so, and then stops... then it locks up in infinite loop.

I am not sure how to structure the code so that it loops \_GlowPower from 0 to 1.0 and then back to 0, over and over... until something happens outside of this code which causes glowactive to become false. I've read up on the different kinds of loops, but something isn't clicking because nothing I've tried has fully worked. (I can easily get the glowing effect to cycle twice, but then it stops.) Please advise!

# Answer
> 0 votes
Turned out, the issue was inside of the loop!

I was changing the glow every single frame, and that was overwhelming Unity.

I changed it instead so that the glow varies every 1/5th of a second. It now also changes by much larger increments: by +/- -0.333 instead of +/- 0.05.

That combination of changes solved the problem. Thanks to all for the thoughtful comments and feedback along the way!

# Answer
> 0 votes
Make a check before the for loop with `Branch` node, if `glowactive` is false, wait for one frame. Equivalent to checking before the start of each round of the full glow animation.

---
Tags: unity, bolt-visual-scripting
---


title: Refresh resource folder during runtime

text:
# Question
Title: Refresh resource folder during runtime
I am directly download some object file (3D Models) inside resource folder and the using Resource.Load I am loading those model in unity. This work perfectly but the problem is I have to refresh the resource folder in order to load resource form there! The first step is downloading the asset then instantiate it through resource.load method. But I am falling in the last step as model import is required which is fine in the editor using assetdatbase refresh but this is not available in runtime.

Edit: I am download obj files in resource and then loading it from resource which is much faster then **Runtime Obj Importer**. Because when I am loading file from persistant path I have to use obj Loader method which is not async is freezing my main thread. Therefore i am preferring resourece.load which is very fast.

# Answer
When you import a 3D model into your project in the Unity Editor, Unity converts the 3D model into an internal mesh format that's optimized specifically for the Unity engine (and stores this somewhere in the `Library` folder inside your project directory).

You noticed that if you download a file into the `Resources` folder in the Editor while the game is playing, you can't immediately access it using `Resources.Load<>`. That's because the Editor hasn't yet parsed the model file into a mesh. Calling `AssetDatabase.Refresh` tells the Editor to look for new files in the Resources folder and convert them into a Unity-friendly format (which is then stored somewhere in the `Library` folder).

When you call `Resources.Load<>`, Unity is *not* reading the original OBJ file and converting it into a mesh; it is loading the previously converted mesh. When you make a build, Unity only includes the converted mesh, not the original OBJ file.

All of the assets in the `Resources` folder are packaged into a single Resources file when you make a build. In a build, the `Resources` folder no longer exists - there is only the Resources file that contains the assets that were already converted into Unity-friendly formats by the Editor. There's no way to add new files to the `Resources` folder in a build because it doesn't even exist in the build.

`Resources.Load<>` is not particularly fast - in fact, it's a messy and inefficient way of loading files at runtime. It just seems fast compared to a runtime file importer because *it doesn't have to import or parse anything*. If you're trying to benchmark it against a runtime model loader, you need to also include the amount of time that `AssetDatabase.Refresh()` takes, because that is what actually parses and converts the mesh data from the OBJ file.

If "Runtime Obj Importer" is not fast enough, you'll either need to modify it yourself, or find a different library that can import OBJ files at runtime.
> 2 votes

---
Tags: unity, c#
---


title: Cube Mapping vs Spherical Mapping

text:
# Question
Title: Cube Mapping vs Spherical Mapping
I am currently researching the difference between Cube Mapping and Spherical Mapping.

Wikipedia says the following:

> In the majority of cases, cube mapping is preferred over the older method of sphere mapping because it eliminates many of the problems that are inherent in sphere mapping such as image distortion, viewpoint dependency, and computational inefficiency. Also, cube mapping provides a much larger capacity to support real-time rendering of reflections relative to sphere mapping because the combination of inefficiency and **viewpoint dependency** severely limits the ability of sphere mapping to be applied when there is a consistently changing viewpoint.

How are cube maps NOT viewpoint dependent?

And does this imply that pretty much in every case Spherical Maps can be replaced by Cube Maps? Or are there exceptions? (some examples would be nice)

# Answer
Regarding reflections:

Cube-maps are capturing the whole reflection space around the pivot on the cube, regardless of the camera's facing direction. Whereas spherical maps capture only the space that is facing the camera (and hence the map needs to be re-drawn for each viewing direction)
> 1 votes

---
Tags: cubemap, sphere
---


# Question
Title: What is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination?
Provided that both objects have rectangular hitboxes, x and y positions and height/width, what is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination?

No engine is being used.

# Answer
If the other thing isn't moving, you can use a raycast. (You didn't say what engine you're working with, but there should be a way to use one for any major engine.) Start at a point just outside of your moving object's hitbox, and cast a ray in the direction of the object's movement, with its length being the length the object will move in however much time you want to "predict." If the ray hits the immobile object, then that's your predicted collision. If not, your path is clear for the length of the ray.
> 0 votes

# Answer
This question is from seventeen months ago so I'm not going to get too deep into it.

Assuming this is some kind of object-avoidance problem, I would suggest that you could just add the "radius" of the stationary object to the "radius" of the moving object then check to see if the centre-line path of your moving object falls within that distance of the stationary object. The actual likelihood of the two objects colliding would depend largely on the aspect ratios of the two hit boxes; the further the aspect ratio is from 1 for either object, the less accurate this method becomes, but should provide a close-enough idea of the likelihood of collision for purposes of object avoidance, if that's the goal.
> 0 votes

---
Tags: collision-detection
---


# Question
Title: Passing a method as a parameter of another method
I'm working on a game project in Unity with a point and click interface and I'm trying to make a method that moves the player towards a target object and invokes another method depending on what the target object is.

I'm running into two problems: first, when I try to pass the method as a parameter, it immediately runs it. For example, the following code is given to the Unity UI to create a button that is supposed to make the player move towards a target and then open a pop up menu. AB\_PathAct is the method that moves the player, the first parameter is the player's destination, and the second parameter is a method, CoMuOpen, which AB\_PathAct is supposed to use when the player reaches the destination. CoMuOpen has it's own parameters. Instead, when the following code runs, both parts happen at once: The player is sent towards the target, and the menu immediately opens. In other words, the code isn't even trying to pass the CoMuOpen call as a parameter of AB\_PathAct, it's just calling it.

```
public void ButtonCMDInvokeTarget()
{
    AB_PathAct(
       r_hit.collider.gameObject,
       CoMuOpen(
           popMenus[1],
           Camera.main.WorldToScreenPoint(
               r_hit.collider.gameObject.transform.position
           )
       ),
       tarDist
    );
}

```

The second problem is that AB\_PathAct isn't actually taking that method as a parameter; when AB\_PathAct reaches its destination, it fails to invoke the method that is its second parameter. I know why this is happening; CoMuOpen returns a string and AB\_PathAct takes a string as it's second parameter. What I want to do is replace AB\_PathAct's string parameter with a method.

To put it simply, I need to replace two lines of AB\_PathAct to make it do what I actually want, but I don't know what to replace them with. Everything in the following code functions correctly except the problem code, which is surrounded by asterisks below (the actual code doesn't have them, obviously).

```
void AB_PathAct(GameObject comTar, **string methodToInvoke**, float tarDist)
{
    if (Vector3.Distance(transform.position, comTar.transform.position) > tarDist)
    {
        agent.destination = comTar.transform.position;
        mr_moveGoal.enabled = true;
        moveGoal.transform.position = new Vector3(comTar.transform.position.x, moveGoal.transform.position.y, comTar.transform.position.z);
    }
    else if (Vector3.Distance(transform.position, comTar.transform.position) <= tarDist)
    {
        agent.ResetPath();
        **StartCoroutine(methodToInvoke);**
    }
}

```

Is it possible to make a method take another method call as a parameter?

EDIT: Here's the CoMuOpen code for reference. It's a very simple function that works as intended when invoked directly or through UnityUI. Returning a string isn't important and I'll probably remove it.

```
public string CoMuOpen(GameObject tarMen, Vector3 tarPos)
    {
    tarMen.transform.position = tarPos;
    tarMen.SetActive(true);
    return "Open Context Menu";
    }

```

# Answer
When you write a method with parentheses after it, like:

```
SomeFunctionWithNoParams()
// or
SomeFunctionWithOneParam(someParameter)

```

...then you are *calling* that function. Assigning this to a variable or passing it as a parameter does not capture a reference to the function as a process, it executes the function and takes its return value (if any) at the end of its execution.

If you want to refer to the function *itself* as a *thing*, you have to leave the parentheses off. This treats it as a delegate \- analagous to a "function pointer" in other languages.

```
System.Action someFunctionDelegate = SomeFunctionWithNoParams;
System.Action<ParameterType> someOtherDelegate = SomeFunctionWithOneParam;

```

But if you don't have parentheses after the function, how do you specify the parameters to use when calling the function? There are a few options...

1. Make a lambda function that "bakes in" the parameters you want, something called a closure.

```
System.Action bakedFunction = () => { SomeFunctionWithOneParam(someParameter); };

DoSomethingThenCallThisFunction(bakedFunction);

```

This makes a new function that takes no arguments, which when executed will call the function you want with the parameter you wanted. Then we can pass a reference to this parameterless function to another function.

Note that this makes a heap allocation to store the new function and the parameter values it's captured.
2. Pass the parameters to the method that will need to make the call, so it can supply them when needed:

```
void DoSomethingThenCallWithParams(System.Action<int, bool> functionToCall, int paramA, bool paramB) {
   DoThing();
   // ...
   functionToCall(paramA, paramB);
}

```

The advantage here is that there's no unnecessary heap allocation. But the downside is that the method you're passing the function into needs to be written with knowledge of the functions that might get passed to it, making it harder to use this when the behaviour of those functions needs to vary wildly.
3. Use an iterator. This gives you a function you can invoke, then pause partway, and finish executing later. In between the frozen state of the function can be passed around as an `IEnumerator` object.

This is how Unity implements its Coroutines, so if you want to `StartCoroutine` anyway, it's a fairly natural fit.

```
IEnumerator DelayedDoThing(int param1, bool param2) {
   // Do something with your parameters

   yield break; // Iterator must have at least one yield statement.
   // If you don't need a pause mid-way, just add a yield break
   // which works like "return" to end execution.
}

void DoAThingThenStartCoroutine(IEnumerator coroutineContent) {
   // Do a thing.
   // ...

   StartCoroutine(coroutineContent);
}

```

Invoke this like so:

```
var thingToDoLater = DelayedDoThing(5, true);

DoThingThenStartCoroutine(thingToDoLater);

```

Similar to the closure, this causes a heap allocation to store the iterator object. But if you're running a coroutine later anyway, that heap allocation is already happening, so it's not an *additional* cost.
> 2 votes

# Answer
DMGregory's answer worked! Here's the new code:

```
void AB_PathAct(GameObject pathTar, float tarDist, System.Action<GameObject, Vector3> methodToInvoke, GameObject actTar, Vector3 actPos)
{
    if (Vector3.Distance(transform.position, pathTar.transform.position) > tarDist)
    {
        agent.destination = pathTar.transform.position;
        mr_moveGoal.enabled = true;
        moveGoal.transform.position = new Vector3(pathTar.transform.position.x, moveGoal.transform.position.y, pathTar.transform.position.z);
    }
    else if (Vector3.Distance(transform.position, pathTar.transform.position) <= tarDist)
    {
        agent.ResetPath();
        methodToInvoke(actTar, actPos);
        print(pathTar.name + methodToInvoke);
    }
}

```

PathAct takes five parameters: the object that is the player's destination, the distance at which the player will stop, the Method that will be called when that destination is reached, and then the two parameters that will be passed to the method: a gameobject, and a vector3 position. Here's an example of what calling it looks like:

```
AB_PathAct(r_hit.collider.gameObject, tarDist, CoMuOpen, popMenus[1], Camera.main.WorldToScreenPoint(r_hit.collider.gameObject.transform.position));

```

The biggest limitation is that the Method that gets passed to PathAct needs to have a GameObject and also a Vector3 as parameters, but that's not that big of a deal, and I might experiment with overrides if I need to.
> 2 votes

---
Tags: unity, c#
---


# Question
Title: What are some "clean" ways to go about reusing the same collection of variables?
I have 4 GameObjects, a character controller script, an enemy manager script, and a damage system script that I would reuse for several different situations in the same way for each. Currently I put all those references into a static class that acts as a wrapper for those said variables but something like this is bad practice. At the same time, I don't want to resort to serializing a bunch of fields in the inspector for each of those situations. Would there be a better approach to this?

# Answer
Scriptable objects are a good solution for storing sets of grouped data that need to be referenced in several spots. Note that scriptable objects are only really good for values that change during edit time. They are not well suited for values that change at runtime.
> 1 votes

---
Tags: unity
---


# Question
Title: Finding GameObject with Tag, excluding this object and its children
I am new to Unity. I'm trying to create a combat game.

I want to access different game objects by tag through the `FindGameObjectWithTag` method, but I want the script to ignore the game object and the children of the game object that contains the script and only reference non children of the game object with the exact tag.

# Answer
You can write a simple function that checks whether an object is this object itself or one of its children/grandchildren/etc:

```
bool IsARelative(GameObject target) {
    var me = transform;
    var t = target.transform;
    while (t != null) {
        if (t == me) return true;
        t = t.parent;
    }
    return false;
}

```

Then use that to filter the collection of all objects with a tag down to only those that are not this object or its descendents:

```
IEnumerator<GameObject> NonRelativesWithTag(string tag) {
    var allWithTag = FindObjectsWithTag(tag);

    foreach(var candidate in allWithTag) {

        if (!IsARelative(candidate))
            yield return candidate;
    }
}

```

You can then walk through that iterator to act on each such object you find:

```
void DoSomethingWithNonRelatives() {
    var nonRelatives = FindNonRelativesWithTag("Some Tag");
    while (nonRelatives.MoveNext()) {
        var found = nonRelatives.current;

        // Do something with `found`.
    }
}

```
> 2 votes

---
Tags: unity, c#
---


# Question
Title: How to make an object move and rotate the same amount as another obejct
**INTRO:**

I am trying to make a camera move around in a fast moving, rotating in all axis, spaceship.... This person has achieved exactly what I need to achieve if that is a good reference for you (go to 5:30):

youtube.com/watch?v=eQt7TwCr6ao&ab\_channel=TomWeiland

**MY PROGRESS:**

I have partially achieved this, by parenting the camera to the first person controller in a static ship and applying changes in transformations from the moving ship to the camera by using the following script. It works position-wise but rotation-wise the camera does not rotate around the ships origin when it rotates, or when I achieve this the camera doesnt move at all.

```
 public Transform TargetParent;

private Vector3 _localPosition;
private Vector3 _localEulerAngel;
private Vector3 _localScale;
private Vector3 _nextScale;

private Vector3 _lastPosition;
private Vector3 _lastEulerAngel;
private Vector3 _lastScale;

void Start()
{
    UpdateLastTranform();
    _localPosition = TargetParent.InverseTransformPoint(transform.position);
    _localEulerAngel = transform.eulerAngles - TargetParent.eulerAngles;
    for (int i = 0; i < 3; i++)
    {
        _localScale[i] = transform.localScale[i] / TargetParent.localScale[i];
    }
    _nextScale = new Vector3(0, 0, 0);
}

void Update()
{
    _localPosition += _lastPosition - transform.position;
    _localEulerAngel += _lastEulerAngel - transform.eulerAngles;
    for (int i = 0; i < 3; i++)
    {
        _nextScale[i] = _localScale[i] * (_lastScale[i] / transform.localScale[i]);
    }
    _localScale = _nextScale;

    transform.position = TargetParent.TransformPoint(_localPosition);
    transform.eulerAngles = TargetParent.eulerAngles + _localEulerAngel;
    for (int i = 0; i < 3; i++)
    {
        _nextScale[i] = TargetParent.localScale[i] * _localScale[i];
    }
    transform.localScale = _nextScale;
    UpdateLastTranform();
}

private void UpdateLastTranform()
{
    _lastPosition = transform.position;
    _lastEulerAngel = transform.eulerAngles;
    _lastScale = transform.localScale;
}

```

**EDIT:**

So this is the scene setup:

**CONCLUSION:**

I need to make the camera be able to move and look around the rigidbody ship that can be rotating in all axis and moving at fast speeds in accordance with the static player controller

# Answer
> 1 votes
If I understand correctly, you have two copies of your spaceship, one that is a moving Rigidbody and one that is stationary. You want the player to walk around the stationary ship, while the camera moves in the same way inside the Rigidbody ship.

Perhaps I'm not understanding something, but it seems like you're making this much more complicated than it needs to be. It seems like all you would need is this:

```
//attach to camera that is a child of the moving spaceship
public class TrackedCamera : MonoBehaviour {
    //the first-person controller should be a child of the stationary spaceship
    [SerializeField] private Transform firstPersonController;

    void Update() {
        //give us the same position and rotation in our parent as the first person controller has in its parent
        transform.localPosition = firstPersonController.localPosition;
        transform.localRotation = firstPersonController.localRotation;
    }
}

```

I'm not sure what you were trying to do with the scale, so I omitted that.

---
Tags: unity, physics, rotation, movement, transformation
---


title: Problem with my walking in gamemaker

text:
# Question
Title: Problem with my walking in gamemaker
Hello I am making a game with my friend and I am the scripter and I wanted to sort out walking he is coming to help me tomorrow. So when I click to go left I go right here is my code

Here is my code to go right

# Answer
> 0 votes
* I believe that you want to change the `X Coordinate`, by `move_speed` to go right, and by `-move_speed` to go left.
* I'm not sure about the sprite. Since I see it says "left" on the name.
* I would expect that if you wanted to flip the sprite the horizontal scaling would be `-1` (and `1` for not flipping it). Not `-2`.

---
Tags: game-maker
---


# Question
Title: Get all images from folder and set them in a list?
How to Load images from folder and set them in a List?

```
public List<GameObject> Img_Re = new List<GameObject>();

// Start is called before the first frame update
void Start()
{
    // Folder path "Assets/Images/Enemies"
}

```

Update 1: Here is an image from unity editor.

I tried to find a solution from using "Resources.LoadAll" but did not give me anything!!

# Answer
This is easiest to do with no scripting at all. Just make your list variable:

```
public List<Sprite> enemySprites;
// or public Sprite[] enemySprites; would work just as well.

```

Select the object holding this script that you want to populate, and click the lock icon at the top-right of the Inspector pane so that it closes: →

Now go select all the sprites you want to assign from your Project pane. You can click on the first one, then hold shift and click on the last one to select everything in the folder in two clicks.

Because the Inspector is locked, clicking on these sprites won't navigate away from showing the list you want to populate.

Now you can drag your selection of all those sprites over the `Enemy Sprites` field in the inspector to assign them all to the list in one go.

But if you really want to do it via script, you can tackle it like so:

```
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class ListOfSprites : MonoBehaviour
{
    #if UNITY_EDITOR
    public string spriteFolder = "Textures/Enemies";

    void OnValidate() {
        string fullPath = $"{Application.dataPath}/{spriteFolder}";
        if (!System.IO.Directory.Exists(fullPath)) {
            return;
        }

        var folders = new string[]{$"Assets/{spriteFolder}"};
        var guids = AssetDatabase.FindAssets("t:Sprite", folders);

        var newSprites = new Sprite[guids.Length];

        bool mismatch;
        if (enemySprites == null) {
            mismatch = true;
            enemySprites = newSprites;
        } else {
            mismatch = newSprites.Length != enemySprites.Length;
        }

        for (int i = 0; i < newSprites.Length; i++) {
            var path = AssetDatabase.GUIDToAssetPath(guids[i]);
            newSprites[i] = AssetDatabase.LoadAssetAtPath<Sprite>(path);
            mismatch |= (i < enemySprites.Length && enemySprites[i] != newSprites[i]);
        }

        if (mismatch) {
            enemySprites = newSprites;
            Debug.Log($"{name} sprite list updated.");
        }
    }
    #endif

    public Sprite[] enemySprites;
}

```

Because this runs in `OnValidate`, it updates any time you change the `spriteFolder` field in the Inspector, at edit time. The resulting list is then serialized into the built version of the game, so there's no searching for the right assets at runtime - you've already stored explicit references to the ones you need.
> 3 votes

---
Tags: unity
---


title: Where did the Composite Collider go?

text:
# Question
Title: Where did the Composite Collider go?
Some of my GameObjects have 2 Sprites nested under them, like how Cat and Snake are nested under Sprites:

The "Cat + Snake" parent GameObject has a Composite Collider 2D and a RigidBody 2D on it (the only other Component is a State Machine with my graphs in it).

Here's the settings for the Cat grandchild (the Snake is identical).

It used to be that if I went into Scene view and clicked on the Cat + Snake in the Hierarchy... I would see the Composite Collider over the Cat and Snake (it looked like a rectangle). Then I could play with the Offset Distance setting, and the rectangle would become a RoundRect.

But I must've tweaked something somehow, and I can no longer see the Composite Collider! But the colliders to seem to be working, as I'm able to click on the Cat, the Snake and the Words.

I'm thinking I must've done something to make the Colliders not appear in Game View, or somehow downgraded them in some respect... any idea what it might have been?

# Answer
Myself, I was able to fix this by navigating to the child colliders, unticking the "used by composite" box, then ticking it again and navigating back to the parent. After repeating that for each child, their combined composite collider gizmos showed up when selecting the parent.
> 1 votes

---
Tags: unity, collider
---


# Question
Title: How to execute functions through the console of a running server build
If I mark the "server build" check box in the building settings, build and then run the .exe, the game or in my case the server, will run as console with no graphics.

But what if I want for example, restart the server, without closing the window and executing the .exe again? Or what if I want for example kick a player?

Basically how I read what someone is typing in this console and execute a function from the build? Or how I do it, if anyone has a better approach. (Like the minecraft server does)

# Answer
> 0 votes
1. Use some local inter-process communication means such as sock files. This way you can log in to the device where the server is located to operate.
2. Develop a management background(a website maybe?), define some instructions, and operate the server in a graphical way. use remote process communication such as rpc, or define your own communication protocol, use tcp/udp/http.
3. Develop a console built into the game(Some games use chat as a base), assign permissions to players, send commands to the server using a common command sending protocol, and parse it yourself.
4. As for restarting the server, This is not an in-game function, it should be some scripts on the server or third-party process hosting software, such as supervisor.

For minecraft basically the third method is used, in the chat panel, special characters(`/`) are used to distinguish normal chat message and server commands.

---
Tags: unity
---


# Question
Title: Box2D make dynamic body fixed on the y axes
I working on a game project using C++ with SMFL and Box2d. I'm basically recreating the game "Jump and Hover", a simple platform game.

In the game ther is an platform thats "hovering" in the air and the player can move it left and right by collideing with it. The player can stand on the platform without make it going down and the player can hit in from below without makeing it going up. So basicly its fixed on the y axes and can only move left/right.

My first idea of implementing this was to set the velocity.y to 0 every round in my general update function that being called every step of the world.

Unfortunately it didnt work. its made the movment up/down very slow but didnt prevent that.

My second idea was to set the gravity scale of the player to zero when he hit the platform from above = stands on it. That worked almost perfectly but when im jumpging on the platform after couple jumps its goes a little bit down. Plus it also still goes up when hitting it from below.

Im out of ideas so Im asking for help.

# Answer
> 0 votes
Set the body type of the platform to kinematic, and this is also a general introduction.

> Bodies have position and velocity. You can apply forces, torques, and impulses to bodies. Bodies can be static, kinematic, or dynamic. Here are the body type definitions:
> ...
> b2\_kinematicBody
> A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces. They can be moved manually by the user, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass, however, Box2D stores zero for the mass and the inverse mass. Kinematic bodies do not collide with other kinematic or static bodies.
> ...

In simple terms, this will make your rigidbody similar to have infinite mass, other than the speed set by the code, other physics interactions will not affect its speed. Here is a similar example.

---
Tags: c++, box2d, collision-resolution
---


# Question
Title: How can I launch a GameObject at a target if I am given everything except for its launch angle?
I am trying to launch an object at a target, given its position, its target position, the launch speed, and the gravity. I am following this formula from Wikipedia:

$$ \theta = arctan \bigg( \frac{v^2 \pm \sqrt{v^4-g(gx^2 + 2yv^2)}}{gx} \bigg) $$

I have simplified the code to the best of my ability, but I still cannot consistently hit the target. I am only considering the taller trajectory, of the two available from the +- choice in the formula.

Does anyone know what I am doing wrong?

```
using UnityEngine;

public class Launcher : MonoBehaviour
{
    public float speed = 10.0f;

    void Start()
    {
        Launch(GameObject.Find("Target").transform);
    }

    public void Launch(Transform target)
    {
        float angle = GetAngle(transform.position, target.position, speed, -Physics2D.gravity.y);
        var forceToAdd = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * speed;
        GetComponent<Rigidbody2D>().AddForce(forceToAdd, ForceMode2D.Impulse);
    }

    private float GetAngle(Vector2 origin, Vector2 destination, float speed, float gravity)
    {
        float angle = 0.0f;

        //Labeling variables to match formula
        float x = Mathf.Abs(destination.x - origin.x);
        float y = Mathf.Abs(destination.y - origin.y);
        float v = speed;
        float g = gravity;

        //Formula seen above
        float valueToBeSquareRooted = Mathf.Pow(v, 4) - g * (g * Mathf.Pow(x, 2) + 2 * y * Mathf.Pow(v, 2));
        if (valueToBeSquareRooted >= 0)
        {
            angle = Mathf.Atan((Mathf.Pow(v, 2) + Mathf.Sqrt(valueToBeSquareRooted)) / g * x);
        }
        else
        {
            //Destination is out of range
        }

        return angle;
    }
}

```

# Answer
I'm a bit skeptical of using `atan` here, because the tangent ratio shoots off to infinity at certain angles, and may lead to numerical errors (even outside of the undefined/divide by zero case for shooting straight up/down).

Using the formulae worked out in this answer, we can parametrize this in terms of the (initially unknown) time to impact, `T`, using the initial `speed` of the projectile:

```
// assuming x, y are the horizontal & vertical offsets from source to target,
// and g is the (positive) gravitational acceleration downwards
// and speed is the (maximum) launch speed of the projectile...

b = speed*speed - y * g
discriminant = b*b - g*g * (x*x + y*y)

if(discriminant < 0)
  return CANNOT_REACH_TARGET; // Out of range, need higher shot velocity.

discRoot = sqrt(discriminant);

// Impact time for the most direct shot that hits.
T_min = sqrt((b - discRoot) * 2 / (g * g));

// Impact time for the highest shot that hits.
T_max = sqrt((b + discRoot) * 2 / (g * g));

```

You can choose either T\_min or T\_max (or something in-between if you want to fire with speeds *up to but not necessarily equal* to some maximum)

(`T_min` is the shallow red trajectory at the bottom, and `T_max` is the tall green one. Any trajectory between them is viable at some feasible speed. When the two merge into the yellow trajectory, the object is out of range.)

Now that we've calculated a value for `T`, the rest is straightforward:

```
vx = x/T;
vy = y/T + T*g/2;

velocity = (vx, vy);

```

You can use this velocity directly (it has a length equal to `speed` by construction), or if you really need to know the angle, you can use `atan2(vy, vx)`

---

**Edit:** to make this applicable to more cases, here's a 3D version:

```
Vector3 toTarget = target.position - transform.position;

// Set up the terms we need to solve the quadratic equations.
float gSquared = Physics.gravity.sqrMagnitude;
float b = speed * speed + Vector3.Dot(toTarget, Physics.gravity);
float discriminant = b * b - gSquared * toTarget.sqrMagnitude;

// Check whether the target is reachable at max speed or less.
if(discriminant < 0) {
    // Target is too far away to hit at this speed.
    // Abort, or fire at max speed in its general direction?
}

float discRoot = Mathf.Sqrt(discriminant);

// Highest shot with the given max speed:
float T_max = Mathf.Sqrt((b + discRoot) * 2f / gSquared);

// Most direct shot with the given max speed:
float T_min = Mathf.Sqrt((b - discRoot) * 2f / gSquared);

// Lowest-speed arc available:
float T_lowEnergy = Mathf.Sqrt(Mathf.Sqrt(toTarget.sqrMagnitude * 4f/gSquared));

float T = // choose T_max, T_min, or some T in-between like T_lowEnergy

// Convert from time-to-hit to a launch velocity:
Vector3 velocity = toTarget / T - Physics.gravity * T / 2f;

// Apply the calculated velocity (do not use force, acceleration, or impulse modes)
projectileBody.AddForce(velocity, ForceMode.VelocityChange);

```
> 19 votes

# Answer
Thanks to DMGregory, I now have a C# extension script which can be used for this.

```
using UnityEngine;

/// <summary>
/// These are extensions for Rigidbody2Ds
/// </summary>
public static class Rigidbody2DExtensions
{
    private const float DefaultGravity = -9.8f;

    /// <summary>
    /// Applies a force to the Rigidbody2D such that it will land, if unobstructed, at the target position.
    /// The arch [0.0f, 1.0f] determines the percent of arch to provide between the minimum and maximum arch.
    /// An arch or 0 or 1 will set the trajectory such that the projectile is launched at max speed.
    /// Any value between 0 and 1 will have a reduced speed.
    /// If target is out of range, it will still fire, but not reach the target.
    /// Use rigidbody2D.IsWithinRange(Vector2, float) to determine if the target is within range ahead of time, if desired.
    /// This only takes the Y gravity into account, and X gravity will not affect the trajectory.
    /// If there is no gravity and no ConstantForce2D is attached, a ConstantForce2D with a gravity of (0.0f, -9.8f) will be attached.
    /// </summary>
    /// <param name="rigidbody2D">The rigidbody2D to apply the force to</param>
    /// <param name="target">The destination for the rigidbody2D</param>
    /// <param name="maxSpeed">The maximum speed to launch at</param>
    /// <param name="arch">The arch to apply to the rigidbody's trajectory</param>
    /// <returns></returns>
    public static void SetTrajectory(this Rigidbody2D rigidbody2D, Vector2 target, float maxSpeed, float arch = 0.5f)
    {
        arch = Mathf.Clamp(arch, 0, 1);
        var origin = rigidbody2D.position;
        float x = target.x - origin.x;
        float y = target.y - origin.y;
        float gravity = -Physics2D.gravity.y;
        if (gravity == 0)
        {
            var constantForce2D = rigidbody2D.GetComponent<ConstantForce2D>();
            if (!constantForce2D)
            {
                Debug.LogWarning("There is no gravity and " + rigidbody2D.name + " does not have a ConstantForce2D attached.  A ConstantForce2D with the default gravity of -9.8f will be added.");
                constantForce2D = rigidbody2D.gameObject.AddComponent<ConstantForce2D>();
                constantForce2D.force = new Vector2(0, DefaultGravity);
            }
            gravity = -constantForce2D.force.y;
        }
        float b = maxSpeed * maxSpeed - y * gravity;
        float discriminant = b * b - gravity * gravity * (x * x + y * y);
        discriminant = Mathf.Max(0, discriminant);
        float discriminantSquareRoot = Mathf.Sqrt(discriminant);
        float minTime = Mathf.Sqrt((b - discriminantSquareRoot) * 2) / Mathf.Abs(gravity);
        float maxTime = Mathf.Sqrt((b + discriminantSquareRoot) * 2) / Mathf.Abs(gravity);
        float time = (maxTime - minTime) * arch + minTime;
        float vx = x / time;
        float vy = y / time + time * gravity / 2;
        var velocity = new Vector2(vx, vy);
        velocity = Vector2.ClampMagnitude(velocity, maxSpeed);
        var impulse = velocity * rigidbody2D.mass;
        rigidbody2D.AddForce(impulse, ForceMode2D.Impulse);
    }

    /// <summary>
    /// Checks if the Rigidbody2D is within range such that if rigidbody2D.SetTrajectory(Vector2, float) is called on it, it will be able to reach its target.
    /// If there is no gravity and no ConstantForce2D is attached, a default gravity of -9.8f will be assumed.
    /// </summary>
    /// <param name="rigidbody2D">The rigidbody2D whose range will be checked</param>
    /// <param name="target">The target used while checking the range</param>
    /// <param name="maxSpeed">The maximum allowed launch speed</param>
    /// <param name="arch">The arch that would be used for the range check</param>
    /// <returns>Whether or not the Rigidbody2D would be within range with the supplied parameters</returns>
    public static bool IsWithinRange(this Rigidbody2D rigidbody2D, Vector2 target, float maxSpeed, float arch = 0.5f)
    {
        arch = Mathf.Clamp(arch, 0, 1);
        var origin = rigidbody2D.position;
        float x = target.x - origin.x;
        float y = target.y - origin.y;
        float gravity = -Physics2D.gravity.y;
        if (gravity == 0)
        {
            var constantForce2D = rigidbody2D.GetComponent<ConstantForce2D>();
            if (!constantForce2D)
            {
                Debug.LogWarning("There is no gravity and " + rigidbody2D.name + " does not have a ConstantForce2D attached.  The default gravity of -9.8f will be assumed.");
                gravity = -DefaultGravity;
            }
            else
            {
                gravity = -constantForce2D.force.y;
            }
        }
        float b = maxSpeed * maxSpeed - y * gravity;
        float discriminant = b * b - gravity * gravity * (x * x + y * y);
        return discriminant >= 0;
    }
}

```
> 3 votes

# Answer
I modified DMGregory and Evorlor's solution a bit as I wanted a 3D arc and wanted to be able to apply a minimum speed if the provided speed wouldn't reach.

```
    /// <summary>
    /// Applies an impulse that will have the rigidbody land at the specified target. The arch is the percent
    /// of arch to provide between the min/max (0 to 1).
    /// </summary>
    public bool ApplyTargetedForce(Rigidbody rRigidBody, Vector3 rTarget, float rSpeed, float rArc = 0.5f, bool rUseMinSpeed = true)
    {
        float lGravity = Physics.gravity.magnitude;
        Vector3 lObjectPosition = rRigidBody.position;
        Vector3 lToTarget = rTarget - lObjectPosition;

        // Find the minimum speed to hit the target
        float lDiscriminantSqrRt = Mathf.Sqrt((lGravity * lGravity) * lToTarget.sqrMagnitude);
        float lMinSpeed = Mathf.Sqrt(lDiscriminantSqrRt) - Vector3.Dot(lToTarget, Physics.gravity);
        if (rSpeed == 0f || (rUseMinSpeed && rSpeed < lMinSpeed)) { rSpeed = lMinSpeed + 0.5f; }

        // Using the speed, our factor for reaching the target
        float b = (rSpeed * rSpeed) + Vector3.Dot(lToTarget, Physics.gravity);
        float lDiscriminant = (b * b) - (lGravity * lGravity) * lToTarget.sqrMagnitude;
        if (lDiscriminant < 0)
        {
            Debug.Log("Not enough force to reach target");
            return false;
        }

        // Determine the min and max time it will take to reach the object.
        lDiscriminantSqrRt = Mathf.Sqrt(lDiscriminant);
        float lMinTime = Mathf.Sqrt((b - lDiscriminantSqrRt) * 2f) / lGravity;
        float lMaxTime = Mathf.Sqrt((b + lDiscriminantSqrRt) * 2f) / lGravity;

        // Determine the force based on our arc value
        Mathf.Clamp(rArc, 0f, 1f);
        float lTime = lMinTime + ((lMaxTime - lMinTime) * rArc);
        Vector3 lForce = new Vector3(lToTarget.x / lTime, (lToTarget.y / lTime) + (lTime * lGravity / 2f), lToTarget.z / lTime);

        // Apply the force
        rRigidBody.AddForce(lForce, ForceMode.Impulse);

        return true;
    }

```
> 2 votes

# Answer
Personally, I wouldn't even bother using any type of complicated formula.

```
GetComponent<Rigidbody2D>.AddForce((target.transform.position - transform.position) * someSortOfMultiplier());

```

It just shoots it in the direction of the target. And if you want to compensate for gravity, distance, etc, set `someSortOfMultiplier()` to be a function that returns a float which will compensate when multiplied with the above code.
> -8 votes

---
Tags: unity, mathematics, projectile-physics, angles, aiming
---


# Question
Title: How to detect if hit by raycast from object with name/tag
**INTRODUCTION:**

In unity, I want to make a dynamic, object use system. Where the main player camera shoots a raycast when left mouse button is clicked and if an object that can be used for example a chair is hit by that specific raycast specifically from the player (there could be other raycasts being shot out from other objects and the player), then that object will run its action, in the chairs case it would disable the player controller and camera and enable its own camera.

**CODE:**

This is the main player camera shoot script:

```
    public Camera cam;
void Update()
{
    if (Input.GetKey(KeyCode.Mouse0) == true) //if left mouse button down
    {
        RaycastHit hit;
        Ray ray = cam.ScreenPointToRay(Input.mousePosition); //shoots raycast from mouse position (cursor lockmode is locked so its from centre of screen)
        if (Physics.Raycast(ray, out hit, 10.0f)) // shoots raycast
        {
          //nothing more needed here, its now up to the object to do the action once it detects this
        }
    }
}

```

This is the initiator script on the object that can be used (the chair in this example):

```
  private void HitByRay(GameObject gameObject) //detects a raycast hitting itself
{
    if(gameObject.name == "Playercam") //detects if the raycast is from camera
    {
        //does the action (this can also just activate a boolean so the action can occur in a different void):
        beingused = true;
        chaircam.gameObject.SetActive(true);
        Player.gameObject.SetActive(false);
        Debug.Log("I was hit by a Ray");
    }
}

```

The scene is this: A quick description of what is going on; chair1 is the gameobject with the initiator script and has no colliders on it but is the parent of 2 colliders that are convex. FPSPlayer is the player controller, Playercam is the camera that shoots the main player camera shoot script. If you need any more information feel free to ask and I will provide it in an edit.

**CONCLUSION:**

My goal is to be able to detect the raycast that is being shot from an object and detect the objects name that shot out that raycast and if that name is the name we want then it does something.

# Answer
> 1 votes
You seem to fundamentally misunderstand how raycasts work. It's not a signal that pokes the object that it hits into action. It's a sensor that reports back to the one firing it what it hit.

It is the responsibility of *the code that fired the ray* to take the next action — objects hit by the ray have no idea they were hit by anything at all unless you write code to tell them so.

You likely want to do something a bit more like this:

```
// First, define an interface for all objects usable this way.
public interface IPlayerUsable {
    void Use();
}

// Implement that interface on each object's script.
public class PerspectiveChange : MonoBehaviour, IPlayerUsable {
    public Camera _camera;
    bool beingUsed;

    void Use() {
        beingUsed = true;
        _camera.gameObject.SetActive(true);
        Player.ganeObject.SetActive(false);
    }
}

// Now your ray routine can look something like this:
void Update() {
    if (Input.GetButtonDown("Use")) {
        RaycastHit hit;
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit, 10.0f)) {
            if (hit.collider.TryGetComponent(out IPlayerUsable usable)) {
                usable.Use();
            }
        }
    }
}

```

---
Tags: unity, c#, raycasting, gameobject, ray
---


title: My character becomes small when moving

text:
# Question
Title: My character becomes small when moving
When I move, my character becomes small, I don't know why though. Here is my code: the first one is to go right, and the second one is for going left.

# Answer
> 2 votes
The *Set Instance Scale* blocks are setting the horizontal scale to `±2` and the vertical scale to `1`. You're scaling **twice** on the X-axis than on the Y-axis, then your sprite is stretched horizontally and the final effect is a squat character.

Just set the horizontal scale to `±1`, so that the sprite only gets flipped around. Otherwise, increase the vertical scale to `2` in both blocks, and the final result will be an object twice as big as the original sprite.

---
Tags: game-maker
---


title: Raycast collision not working

text:
# Question
Title: Raycast collision not working
I've tried to do a gun mechanic for my 3d game but when I tried to write ray cast it didn't work only layer that is printed is 0 even though it shoots and gets stopped by an obstacle here's the important code

```
private void Update()
{
    if (!Input.GetButton("Fire1") || !(Time.time > nextFire))
    {
        return;
    }
    nextFire = Time.time + fireRate;
    Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.5f));
    laserLine.SetPosition(0, gunEnd.position);
    if (Physics.Raycast(rayOrigin, fpsCam.transform.forward, out var hit, weaponRange))
    {
        print(hit.collider.gameObject.layer);
        if (hit.collider.gameObject.layer == enemyLayer)
        {
            laserLine.SetPosition(1, hit.point);
            //decrease enemy health
        }
        else
        {
            laserLine.SetPosition(1, rayOrigin + fpsCam.transform.forward * weaponRange);
        }
    }
}

```

all of the variables are serialaized on inspector window and no mistakes were made . i even checked if the enemy did have a working collider which it did and the layer output was 3(enemy)

# Answer
I would use tags instead of layers. If you are looking to detect enemy hit collision with raycast, layers are generally not the best method.

Call `FireWeapon()` whenever you want to fire a Raycast. Create a new tag in the unity editor called "Enemy". Whenever the ray hits a collider with the tag assigned Enemy, you should be able to handle whatever commands needed. Realistically, you can just use my raycast if check in your current function if everything is working as it should. The ray will be forward out from the cameras front direction.

Please let me know if I can be of any further help

```
void FireWeapon() {
//Created a camera type with name PlayerCamera
float weaponRange = 150f;
if (Physics.Raycast(PlayerCamera.transform.position, PlayerCamera.transform.forward, out RaycastHit hit, weaponRange)) {
    if (hit.collider.CompareTag("Enemy")) {
        // Decrease health
    }
}

```
> 0 votes

---
Tags: unity, c#
---


# Question
Title: SDL2 and TmxLite (Tiled) (Reading the actual TILE data from the layer)
I am trying to make use of the Tiled Map Editor for my SDL2 projects. (By using the TMXLITE parser from Fallahn on Github) https://github.com/fallahn/tmxlite

```
#include "PlayingField.h"

#include <tmxlite/Map.hpp>
#include <tmxlite/Layer.hpp>
#include <tmxlite/TileLayer.hpp>
#include <tmxlite/ObjectGroup.hpp>

void PlayingField::InitPlayingField()
{
    tmx::Map map;
    map.load("Assets/pitch.tmx");
    auto layers=map.getLayers();
}

```

I have used this editor in the past with SFML, Unity and other C# frameworks but this was some years ago.

As you can see from my code, I believe I have correctly linked and have indeed loaded the map into memory. I also have the array of `layers` now.

But I am reading through all the docs and really struggling where to turn next.

In this example, I have just 1 layer. I am not even yet concerned with drawing the tiles to screen. But what I wanted from the TMX export really is just the map of the tiles. In other words, I want to create an array (or std::vector) or all the tiles.

My `Tile` would be simply X,Y location floats and the BMP image for that tile. I am looking here: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/ and I see the properties `tileoffset` and `image` but I do not see how to access those from the TMX file using TmxLite. (I did read somewhere TmxLite can't use Embedded assets. Well even that would be ok I can load the tile textures myself if necessary but still I do not see how the TMX file is used to layout and position these tiles.)

(Note: For this small example I could pretty easily wrote my own file format for the maps and using std::getline I could make some simple/crappy way of reading the file. The whole point to my exercise today is trying to learn Tiled specifically so that I can begin to make use of Tiled Editors full features (and also for making very complex maps).

Sorry for the broad question but I am just hoping to receive correct help within a fast time so that I can get on with more game dev :D (I did consider writing on TmxLite github support pages but I felt it might be better asking here first).

# Answer
> 1 votes
Well I doubt this is the proper way to use this. But I was able to get the array of Tiles (which was essentially just an array of int 'ID') as follows:

```
void PlayingField::InitPlayingField()
{
    tmx::Map map;
    map.load("Assets/pitch.tmx");
    const auto& layers=map.getLayers();
    const auto& tiles=layers[0]->getLayerAs<tmx::TileLayer>().getTiles();

    printf("Chunks Count=%d\n", (int)tiles.size());
    for(int i=0; i<tiles.size(); i++)
    {
        printf("tile id=%d\n", (int)tiles[i].ID);
    }

}

```

With this (and as I know how wide the map is). I can use that to draw my tiled background with a little extra code.

---
Tags: c++, 2d, sdl2, tiled
---


# Question
Title: Unity gameObject character stuck in T pose for scene but animations work fine when playing game
I want to put a sword in his hand but it is difficult in that T pose.
I have a nice idle animation from Mixamo (model also from Mixamo) that transitions to walk which is working fine.
My other model, playerNinja is in his idle position in the Scene even without playing it, like this:

How can I get the top one to get in his idle position in the Editor Scene tab?

# Answer
Welcome!

By default, your model will always be on TPose in Edit Mode, this is because the skeleton of your model was setup like that when it was modeled by Mixamo. The only way to display, or preview your animations, would be by using the Animation window, selecting your animation (while selecting your model with an Animator component attached to it), and hit on the "Preview" button.

I would not recommend to use the second model you have, since it's there only for demonstration purposes. You should only use one model (the one with the TPose) with as many animations as you wish, but not otherwise (many models with different animations each one, for only one character. Though there may be a reason on why you would want that setup). Performance and final file size (the size of your build) are the primary concern here.

Anyway, you'll need to adjust the sword in relation to the TPose of the character, that's usually how it's done. I *think* that if you preview the animation and lock the animation window, you could technically adjust the sword according to the animation in preview, but I have never tried that before.
> 2 votes

---
Tags: unity, editors
---


# Question
Title: Adding a color picker to a Scriptable Object
I made a Scriptable Object, and added a bunch of fields to it: string, Vector3, Sprite, etc.

So far, so good! I'd like to also add a field with a simple color picker in it, that allows me to set the color of some text.

I see that I can easily add a Material and use the color from there, but I'm hoping there's a more direct way I can add a color picker to the Scriptable Object. Anyone know?

# Answer
> 3 votes
This was achieved pretty easily by adding the following in your class that inherits `ScriptableObject`

```
public Color RarityColor;

```

The `Color` type as `public` should get it to show

---
Tags: unity, scriptable-object
---