#🖼️┃2d-tools

1 messages · Page 49 of 1

late viper
#

thanks

olive cloak
#

Hello, im new to unity and im trying to add a player, but when i add boxcollider 2d and riggid body 2d it just disapper when i run the game

late viper
olive cloak
#

there is a collider

late viper
olive cloak
#

how to i add a collider to the tile map?

#

i found the problem

#

the chrattar spawned inside the collider

limpid drift
#
 animator.SetFloat("X", runspeed);
        if (Input.GetKey("d") || Input.GetKey("right"))
        {
            rb2d.velocity = new Vector2(runspeed,rb2d.velocity.x);
            if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
                
            spriteRenderer.flipX = false;
        }
        else if (Input.GetKey("a") || Input.GetKey("left"))
        {
            rb2d.velocity = new Vector2(-runspeed,rb2d.velocity.x);
            if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
            spriteRenderer.flipX = true;
        }
``` can someone tell me whats wrong with me code because my player does not run left to right anymore instead it does this
turbid heart
#

rb2d.velocity = new Vector2(runspeed,rb2d.velocity.x);
you're setting your velocity on the x and y axis. you set your runspeed to the x-axis, and the rb2d.velocity.x to the y axis @limpid drift

limpid drift
#

how do i set the rb2d.velocity.x to the x axis?

turbid heart
#

when you assign a Vector2 to your rb2d.velocity, it's new Vector2(yourXVelocity, yourYVelocity)

#

do you know what velocity is?

limpid drift
#

speed right?

#

how fast it goes and stuff

turbid heart
#

speed with a direction

#

you assign velocity like this new Vector2(yourXVelocity, yourYVelocity)

#

so if you only wanted to move it on the x axis, set your Y velocity to 0

limpid drift
#

ooooh

#

so it should be ```csharp
rb2d.velocity = new Vector2(runspeed,0);

#

atleast thats what i think?

turbid heart
#

try it and see

limpid drift
#

now its acting really weird

#

for some reason it worked when i made it ```csharp
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.y);
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)

        spriteRenderer.flipX = false;
    }
    else if (Input.GetKey("a") || Input.GetKey("left"))
    {
        rb2d.velocity = new Vector2(runspeed,rb2d.velocity.y);
        if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
        spriteRenderer.flipX = true;
    }
#

but i got told thats wrong

#

but if i make it ```csharp
rb2d.velocity = new Vector2(runspeed,0);

turbid heart
#

yeah, i dont know your full context, i'm only assuming you want to move your player left and right, instead of diagonally

#

hang on

#

I might have misunderstood you

#

I'm sorry

limpid drift
#

yeah i want it to move left and right

turbid heart
#

you would want rb2d.velocity.y in your y velocity to maintain its y axis momentum, so you can put that back

#

yeah, sorry. you should revert back your code for now, I have no idea

#

is there a place you add to your y velocity?

limpid drift
#

yeah so when the lines were ```csharp
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.y);

#

but when i change it to ```csharp
rb2d.velocity = new Vector2(runspeed,rb2d.velocity.x);

#

i honestly dont understand this anymore

turbid heart
#

can you please take a video of this midfloat animation? @limpid drift

snow willow
limpid drift
#

thats what i got told to do in a other discord

#

they said this was wrong

#

because of the rb2d.velocity.y should be rb2d.velocity.x

#

and when i changed that my player started floating like the vid i just sent

snow willow
#

I think they were talking about in the if (Mathf.Abs(rb2d.velocity.y) < 0.001f) part

#

not the part you changed

limpid drift
#

oh

#

so the ```csharp
if (Mathf.Abs(rb2d.velocity.y) < 0.001f)

#
 if (Mathf.Abs(rb2d.velocity.x) < 0.001f)
snow willow
#

yes... of course - you want to check the horizontal velocity of your character to flip it, right?

limpid drift
#

but thats the part that confusses the fuck out of me

#

because ```csharp
if (Mathf.Abs(rb2d.velocity.x) < 0.001f)

#

does not flip

#
if (Mathf.Abs(rb2d.velocity.y) < 0.001f)
#

it does flip

#

and i dont understand why the hell it works like that

turbid heart
#

why do you do Mathf.Abs? I can see you set your x velocity to -runSpeed

snow willow
#

oh yeah lol

turbid heart
#

Mathf.Abs makes it never negative @limpid drift

snow willow
#

don't use Abs

#

it's absolute value

turbid heart
#

and.. why do < 0.001f? why not just < 0f?

limpid drift
#

so ```csharp
if (rb2d.velocity.y)<0)

turbid heart
#

no

snow willow
#

x, not y

turbid heart
#

the x axis

limpid drift
#

ah yeah x my bad

#

gives me this error

#

so no idea why it does allow it with mathf.abs

turbid heart
#

check your brackets, and you dont need a ; there

#

you didnt put one for your Input.GetKey if, so why would you need one there? @limpid drift

limpid drift
#

found it had one ) too many

#

and the ;

cursive heart
dusky wagon
#

Another simple question, but can you offset a sprite from its center point? In my script the character gets flipped if hi changes direction, but because my character has a long sword in the front it looks like the entire character changes its position

#

Nevermind I figured it out

viral moss
#

*and that invert is not turned on

cursive heart
viral moss
#

ah okay

cursive heart
#

And I just went to the input from the axis and managed to configure it, thanks for help

silver walrus
#

ANything wrong with this code? The ''impulse'' is not happening when the player slides in the wall and press space

vocal condor
#

Separate the logic from input polling.

#

Input polling should be handled in Update and Physics should be dealt with in Fixed Update. Not doing so would produce strange effects (polling in fixed update will have you missing inputs - whereas doing physics in Update will not properly interpolate; causing delays)

left nest
#

I am trying to make a certain gameobject appear and then after a few seconds disappear and have a new gameobject appear but I am having problems. I am using Invoke to start certain functions to begin those functions, but in unity it comes up with the error message: "_ManagerScript.LBA() is a method which is not valid in the given context" Here is my code:

using UnityEngine;

public class _ManagerScript : MonoBehaviour
{
    public float LBA_Lifetime;
    public float LBA_Warntime;
    public GameObject LBA_Warn;
    public GameObject LBAA;


    void Awake()
    {
        LBA.SetActive(false);
        LBA_Warn.SetActive(false);
        Invoke("LBAW", LBA_Warntime);
    }

    void LBAW()
    {
        LBA_Warn.SetActive(true);
        Invoke("LBA", LBA_Warntime);
    }

    void LBA()
    {
        LBA.SetActive(true);
        LBA_Warn.SetActive(false);
    }
}


How can I fix this?

left nest
#

Invoke

turbid heart
#

which line has the error?

left nest
#

40:52

turbid heart
#

we cant see line numbers in discord. which line is it

#

you can double click the error in the console and it'll take you to it

left nest
#

LBA.SetActive(false); to LBA.SetActive(true);

turbid heart
left nest
#

oh

turbid heart
#

maybe a lesson in naming your methods and variables to something more intuitive

left nest
#

ok thank you

#

thank you!

turbid heart
left nest
#

yes

sick lagoon
#

Hey, I am making a 2D platformer for Android.
When running it in the unity Game View, the movement is smooth and good,
but when exporting it to my phone the player jumps fine but he moves 100x slower.

#

I cant attach code tho, it blocks me

late viper
sick lagoon
#

Hmm, makes sense

#

Ill debug it and update about it

sick lagoon
late viper
sick lagoon
#

Checking

#

It looks like when on my phone the ground has so much more drag then in unity

#

As when im jumping it starts accelerating but on ground not

sick lagoon
#

Tho, Im facing another problem, when landing after a jump, the character clips into the ground and bounces back up, have someone encountered this problem?

sick lagoon
sick lagoon
marble isle
viral moss
marble isle
#

im pretty new to game dev so im not too sure how to explain things haha

viral moss
#

Sorry but i'll pass </3 in a call w/ friends.
But you should probably try to describe what's supposed to happen

marble isle
viral moss
#

Alright well for the animations, I would recommend watching a guide on how they work in general.
https://www.youtube.com/watch?v=hkaysu1Z-N8
I think this one's p decent.
As for the 'spaz', I assume it's because the enemy is trying to reach the players location.
You could do a check for if it's very close to the player with something like "if transform.x is between player.x -0.5 & player.x +0.5" so it would stop chasing the player if it's basically on top or below them

Let’s animate our character!

● Check out Skillshare: https://skl.sh/brackeys8

● Watch Player Movement: https://youtu.be/dwcT-Dch0bA

● Download the Project: https://bit.ly/2KK5AG8
● Character Controller: https://bit.ly/2MQAkmu
● Get the 2D Sprites: https://bit.ly/2KOkwjt

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

···········...

▶ Play video
marble isle
#

thnx. ill check it out

marble isle
pseudo wave
#

hello does anyone know why my MovingBlock function is not working?

#

the playerScript.change.x and playerScript.change.y are the raw inputs of the player direction

#

so it gives +1, -1 or 0

#

the logic is moving the block in the direction the player is facing 1 unit, when pressing Z and player is in range

#

player is in range is working properly

#

the first line of the while loop inside the IEnumerator is just while the distance is > than a very small amount (Mathf.epsilon)

runic cipher
#

[tilemap question] Hi everybody. I'm trying to extend tilebase to store data within each tile on a tilemap. Does each tile exist as its own separate object, meaning I can store data in each individual tile, or are all tiles copies of a base tile? Thanks!

dense flame
#

Each individual tile stores it’s own value if you use scriptable tiles

runic cipher
#

Does this also hold true for the value stored in tileData, ie the sprites and such?

marble isle
#

my characters animation wont go back to idle even tho i used else

#

anything i have done wrong?

snow willow
#

you need to have the appropriate transitions set up

knotty barn
#

@marble isle You sure you are calling ChasePlayer when the else condition is true?

snow willow
#

also that

marble isle
#

isRunning true causes the run animation and false causes idle animation

snow willow
#

I would play the game with the animation window open and the Animator selected,. and watch the state machine

#

you'll want to make sure the correct parameter values are set at the correct time and that the state machine is properly transitioning to the desired states

marble isle
#

im pretty new to game development so im struggling a little here haha. i have been experimenting for hours and finally got the run animation to work, it just wont go back to idle

snow willow
#

What I just said is, in my opinion, the best way to debug animation issues

knotty barn
#

Is the value changing in Animator?

marble isle
#

could i upload a video for you to have a look. not to sure whats going on

knotty barn
#

Just look for if the isRunning bool is changing in the animator

#

You should see the currently selected GameObject's animator state in the animator window while you are in play mode

marble isle
#

or could one of you help out on a call. i have alot of bugs right now haha. it now only starts the animation if i am on the right of the sprite

#

but continues the run animation forever

#

i believe its my code but idk where to start in fixing it. been tryna fix this for hours

snow willow
#

sounds like you have more than one issue going on. Try to focus on one thing at a time

marble isle
#

@snow willow @knotty barn

snow willow
#

That should just be isRunning -> false

#

delete the "notRunning" parameter. It's confusing and redundant. Delete it entirely from the animator

#

isRunning can already be true or false

marble isle
#

god im dumb haha. i was messing around with other perimeters and must have forgotten to change one back. im super fresh to game development so im literally rocks for brains haha.

marble isle
#

holy shit i fucking did it

silver walrus
#

Hi! I followed a tutorial on a wall jump code and got this. Now, for some reason it is not working. I can jump into the wall, the character starts sliding but no matter what i press, nothing happens. Any ideas?

#

Thx in advance!

fallen flicker
#

Maybe instead of using Keycode.Space try and use Input.GetKeyDown("Jump") and see if that fixes it

turbid heart
silver walrus
#

Got fixing it, I just had to remove the WallJump mechanic and leave only the wallhop

fallen flicker
#

You'd have to define one but I believe it is auto set as the space bar

#

Nice

silver walrus
#

also, changing to Jump helped

untold fox
#

Can someone help me with a script ?

#

Im trying to make the player jump but when im trying to jump it doesn't work

#

Thats the script

using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public float movementSpeed;
    public Rigidbody2D rb;

    public float jumpForce = 20f;
    public Transform feet;
    public LayerMask groundLayers;

    float mx;
    bool isGrounded;

    private void Update() {
        mx = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            Jump();
        }
    }

    private void FixedUpdate() {
        Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);

        rb.velocity = movement;
    }

    void Jump()
    {
        Vector2 movement = new Vector2(rb.velocity.x, jumpForce);

        rb.velocity = movement;
    }

    public bool IsGrounded ()
    {
        Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);

        if (groundCheck != null && groundCheck.gameObject != null)
        {
            return true;
        }

        return false;
    }
}
#

There are no errors

#

Its just doesn't work

craggy kite
untold fox
craggy kite
#

So did you check both? @untold fox just debug.log both statements and see what you get

craggy kite
#

Are they both not null?

untold fox
craggy kite
#

So it is returning true?

#

Did you debug.log your jump, to check it is being called?

untold fox
#

wdym

craggy kite
#

Debug.Log("Jump") in ypur function...

untold fox
craggy kite
#

Nope, sorry, working right now and I dont do DM support

untold fox
#

k

bronze reef
#

I have a question about coding but not directly about my code

#

I literally just started coding today.

#

And I am pacing myself literally only making a square move left and right and jump

#

But everything I did today I will have to look back to because I won't be able to remember it.

#

So my question is, Will I be able to write it off heart once I write it more and more?

late viper
#

your goal isn't to memorize how to make it move, it is to understand the concepts that make it move

#

but yes as you get experience it will be easier to write code

bronze reef
#

Ok. I am trying my best as I am writing it to understand what is happening, and I am understanding some things but I still don't know how everything works.

#

It took me 5 hours just to make a square move and jump.

late viper
#

thats fine, everyone starts somewhere

leaden sky
#

how can I change the sprite sheet that is used for an animation. So I have this sprite sheet for a player spawn. But I have it for 4 different colors. Do I have to create a seperate animation clip for each?

craggy kite
leaden sky
#

so player 1 = greedn, 2 red etc

craggy kite
#

you could just use unity to color the texture then, would be a workaround. Otherwise you could swap textures with alternate textures / sprites, check google for alternative sprite textures.

leaden sky
#

thanks I will see what i can find

twin anvil
#

How can I make it so whenever my mouse is on the left side of the screen my character is facing that direction? I don’t want the character to follow the mouse, just change direction left or right depending.

left nest
#

what have you tried so far?

twin anvil
#

I’ve looked at some forum posts about the same type of thing but couldn’t get it to work

left nest
#

Well you could so something like this:

#

Put this is void Update and make a public float called offset place it on the player and if it doesn't fully face the mouse increase offset and eventually it will,

Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
twin anvil
#

Ok thank you so much

twin anvil
marble isle
hollow crown
#

assets cannot reference in-scene data

#

so those references will be prefab overrides in the scene

marble isle
#

is that possible?

hollow crown
#

Generally whatever spawns the NPC should have the in-scene references

#

and pass them to the NPC when they are instanced

turbid heart
marble isle
honest palm
#

Bit of an odd question. Does anyone know how I might create a vector from an angle and a direction?

Currently I'm trying to make a character turn to face a left and right angle from their current up position. Like a sort of scan or sweep across their field of vision. But to do so, I need them to be able to look to the left and right of their current facing direction by a given angle.

hollow crown
marble isle
left nest
#

you could code it to go to the position of any gameobjects with the tag player

#

or raycasts to detect if the player is near to come and attack it

hollow crown
#

Not sure what you mean, you don't need multiple scenes, the entire issue here is that references can only exist in the scene, or to or between assets.
If the spawner has the in-scene reference, and references the prefab asset, then it can configure the instance when the prefab is spawned

marble isle
marble isle
hollow crown
#

You can disable the gameobject

twin anvil
turbid heart
twin anvil
#

oh got it

#

that makes sense

turbid heart
#

Is this 2d? Flipping your sprite is the easier part 🙂 you can look it up

twin anvil
#

it's 2.5d yeah

#

i think ik how to flip it

#

just rotate it, but i still don't know how to add the mouse on the left and right to the rotation

left nest
#

to flip it you can just invert the x scale

twin anvil
#

yeah

#

that's not the part im having the problems with

#

it's the checking which side of the screen the mouse is on

left nest
#

ah

green tapir
twin anvil
#

I don't think so. Does this make the sprite follow the mouse around directly?

green tapir
#

no. just to clarify, is this pure 2d or 2.5?

#

because one you have to project the mouse.

twin anvil
#

2d

#

im doing it in a 2d manner

green tapir
#

well then that should pretty much do that?

left nest
#

isn't that putting the sprites position the same as the mouses position

twin anvil
#

are you referring to it make something rotate around to follow the cursor? because if so, that's not what i need

#

i just need the sprite to flip from left to right

green tapir
#

oh

twin anvil
#

if the cursor is on the left or right, not follow it directly

green tapir
#

so to clarify, you want the sprite to flip if the mouse is on the left side of the screen?

left nest
#

to get this straight you want to the sprite to to face the direction the mouse is so if the mouse is the right of the player it faces right if the mouse is the left of the player it faces left

twin anvil
#

yes

green tapir
#

and then back when it goes back to the right?

twin anvil
#

indeed

left nest
#

ok

green tapir
#

are you rotating or flipping anything anywhere else, just to figure out how I want to give this to you?

#

because there are a lot of ways to skin this cat.

twin anvil
#

im having the player sprite flip, but have the hand also rotate around him towards the mouse

#

so the player will flip left and right only

#

and the hand will follow the cursor directly

green tapir
#

does it currently do a sprite flip?

twin anvil
#

?

green tapir
#

like, it doesn't currently flip at all?

twin anvil
#

no

#

when i move the mouse the player doesn't flip at all

left nest
#

when the player moves right does it flip to face right and when it moves left does it flip to be left?

twin anvil
#

no, i want the player to be able to walk backwards

green tapir
#

okay, so that bit I gave you above is half the equation. You want to take that mousetoscreenspace variable, and then get your resolution, then you can set up an "If it's less than half the res, sprite.localScale *=-1" or however you want to do the flip

twin anvil
#

so when he moves or pressed wasd it doesn't change

#

ok

green tapir
#

just using the mousetoscreenspace.x

#

not the whole vector3

#

@twin anvil var screenPoint = Input.mousePosition; screenPoint.z = 10.0f; //distance of the plane from the camera var tracker = Camera.main.ScreenToWorldPoint(screenPoint).x; print(tracker); var reso = Screen.currentResolution.width; if (tracker < 0) { transform.localScale = new Vector3(-1, 1, 1f); } else { transform.localScale = new Vector3(1, 1, 1f); }

#

this seems to do what you want basically.

twin anvil
#

it seems to be working how i want it, but the center of the screen is for some reason offset to the left a little.

#

oh i think i know why

#

would this work with a camera that follows the player?

green tapir
#

Yeah, though it might goof if the distance to the screen changes.

#

but should basically work in 2d.

#

I'll confirm.

#

seems fine

twin anvil
#

for me whenever i move the player it drifts off from where the center of the screen is

#

i even watched the tracker that you put in, and whenever i move to the right without moving my mouse the number goes up

green tapir
#

hmmm.

#

okay

#
        {
            sprite.transform.localScale = new Vector3(-1, 1, 1f);
        }
        else
        {
            sprite.transform.localScale = new Vector3(1, 1, 1f);
        }```try that
#

note that this does require the game to actually have a set resolution.

#

just "16:9" or free aspect won't work.

twin anvil
#

it's telling me sprite doesn't exist in the current context

green tapir
#

oh, sorry, that's a holdover from trying something else.

#

just get rid of sprite.

twin anvil
#

oh ok

#

it's works!

green tapir
#

actually, just do Screen.width

twin anvil
#

thank you so much dude

green tapir
#

Screen.Width just takes the cameras current res, which will probably work better for you.

#

Seems like.

#

for this context

twin anvil
#

ok got it

green tapir
#

what was that about rotation?

twin anvil
#

what about rotation

green tapir
#

you said something about rotation I thought. If no, have a good one, hahaha

twin anvil
#

no it was just another way i was going to flip the sprite

#

but this works fine, have a good one

#

thank you a lot

twin anvil
#

ok, im back again

#

I'm trying to make my players hand rotate around his body

#

but the problem i'm having is, is when the hand/mouse gets above the character at a 90 degree angle and goes past it the hand goes to the feet area instead of the head

#

ik what the problem is but don't know how to fix it

#

it has something to do with the thing I just had a problem with, whenever the character turns around (the scale is changed to a negative) it also changes the scale of the hand, and if i take the hand out of the children of the player it won't move with the player

marble isle
#

i have my enemy face my character when on their left or right but when im above the enemy it has a spaz. is there any way to fix this. i want it to go idle when the playable character is directly above or below so when writing if (transform.position.y < Player.position.y) the enemy goes idle even if i do the tiniest jump (this code was removed before making the video so i could show the spaz haha)

vocal condor
marble isle
vocal condor
#

Where minDist is the minimum offset before acting.

vocal condor
marble isle
#

im pretty new to game dev so im not very knowledgeable in the language

#

should i put my code in here?

vocal condor
#

Basically if the player is left of us PLUS some minimum distance, go left. Else if the player is right if us PLUS some minimum (maximum of you're wanting to think of it as coordinates), go right.

marble isle
#

ah. i have all of that set up. the character already follows me. i just want it to go idle when im directly above or below it

vocal condor
#

Which is why I mentioned the minimum and maximum distance before changing directions; spazzing?

#

I am not able to watch the video and am simply assuming based on what you said.

marble isle
#

when i am directly above or below the enemy it doesnt know which way to face as i am neither on the left or right of it so it just looks both left and right at a very high speed haha

vocal condor
#

You simply need to set a minimum.

#

So if it's within a minimum it doesn't bother chasing/facing your player.

#

I've got to go now, good luck.

marble isle
#

ok thnx

worldly leaf
hollow crown
#

select something and press F

#

then zoom into it

worldly leaf
#

@hollow crown ah thank you dude

torpid locust
#

Hey! I'm trying to make a game where when I pickup a key it changes the color of one game object(door) and I worked out how to make it disappear but I don't know how to connect this with another object because I used a ontrigger thing to make the key disappear.

leaden sky
radiant wigeon
#

How would I make a sprite (the player) land on another sprite (the map)?

#

Would changing the z axis do anything?

#

could I use ```cs
if (Physics.OverlapSphere(groundCheckTransform.position, 0.1f).Length == 0)

to check if its on the ground?
#

no that wont work

#

wait yes it does nvm

#

wait nvm again

radiant wigeon
#

Like how would I make a 2d object stop another 2d object from falling through it?

plush coyote
#

put a 2D collider on both objects..

#

and a rigidbody on your player

radiant wigeon
#

I have a Rigidbody but thx

#

@plush coyote does it matter which type of 2d collider?

plush coyote
#

it has to be a Rigidbody2D and a Collider2D

#

no it doesnt really matter what type of 2D collider

#

as long as it sort of matches the object

#

capsules and boxes are the most common

radiant wigeon
plush coyote
#

just like any other component, so yes

radiant wigeon
# plush coyote just like any other component, so yes

I get this error when I do:

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

public class Player : MonoBehaviour {

    bool jumpkeyWasPressed;
    float horizonalInput;
    Rigidbody rigidbodyComponent;
    [SerializeField] Transform groundCheckTransform;

    void Start() {
        rigidbody2DComponent = GetComponent<Rigidbody2D>();
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) {
            jumpkeyWasPressed = true;
        }

        horizonalInput = Input.GetAxis("Horizontal");
    }

    void FixedUpdate() {
        rigidbody2DComponent.velocity = new Vector3(horizonalInput, rigidbody2DComponent.velocity.y, 0);

        if (jumpkeyWasPressed) {
            rigidbody2DComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
            jumpkeyWasPressed = false;
        }
    }
}

Assets\Scripts\Player.cs(28,13): error CS0103: The name 'rigidbody2DComponent' does not exist in the current context

#

wait lemme edit

plush coyote
#

you didnt spell your own variable name the way its supposed to be

radiant wigeon
#

I realized after I sent the msg lol

#

I get this err now

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

public class Player : MonoBehaviour {

    bool jumpkeyWasPressed;
    float horizonalInput;
    Rigidbody2D rigidbody2DComponent;
    [SerializeField] Transform groundCheckTransform;

    void Start() {
        rigidbody2DComponent = GetComponent<Rigidbody2D>();
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) {
            jumpkeyWasPressed = true;
        }

        horizonalInput = Input.GetAxis("Horizontal");
    }

    void FixedUpdate() {
        rigidbody2DComponent.velocity = new Vector3(horizonalInput, rigidbody2DComponent.velocity.y, 0);

        if (jumpkeyWasPressed) {
            rigidbody2DComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
            jumpkeyWasPressed = false;
        }
    }
}

Assets\Scripts\Player.cs(28,59): error CS1503: Argument 2: cannot convert from 'UnityEngine.ForceMode' to 'UnityEngine.ForceMode2D'

plush coyote
#

its exactly as it says, the 2D version of addforce uses ForceMode2D

#

not ForceMode

#

and you should use Impulse for the forcemode2d type instead

#

since I dont think VelocityChange exists in the 2d version

radiant wigeon
#

yea VelocityChange wont work

plush coyote
#

if you want it to actually just completely change the velocity than set the Y velocity to 0 before you jump, then add impulse force

radiant wigeon
#

How would I do that?

plush coyote
#
Vector2 newVel = rigidbody2DComponent.velocity;
newVel.y = 0f;
rigidbody2DComponent.velocity = newVel;
#

since you cant directly set the y value, you have to do that

#

as for the impulse, you just need to switch ForceMode to ForceMode2D like I said earlier

#

then Impulse instead of VelocityChange

radiant wigeon
#

ok

#

wait im still confused

#

now I just float through the block very slowly

#

@plush coyote

#

I just need to know how to let a block land on another block

plush coyote
#

if you dont understand, look on google for basic explanations of how physics components work in unity

radiant wigeon
#

lol it turns out I forgot to attach a collider

still tendon
#

im trying to make a top down fishing game but i dont know how to make the fishing mechanic, i want it to be randomly base for example one fish has A 2% chance of spawning and another has 5% chance of spawning, anyone have any good code? or video tutorial that would help

dire salmon
#

how could i convert this to be smooth turning with a turn speed?

Vector3 dir = Input.mousePosition - pos;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);```
brazen snow
#

Can someone help me with this ?

#

When im trying to jump again it doesn't work

dire salmon
#

code?

dusky wagon
#

How can I make an object with a rigid body be harder to push without making it super heavy?

snow willow
#

Maybe give it a physics material with more friction?

dusky wagon
#

Ive tested a bit and the only thing I found to prevent the player from throwing the object around like nothing was to make the object very heave but that made it fall to the ground instantly-

dusky wagon
gilded rover
#

do you have any tutorials for a 2d shooting system?
like, can you recommend any?

turbid heart
gilded rover
#

yea

turbid heart
#

well you need to be more specific on the kind of 2d shooting system you're after

gilded rover
#

all of them are platformer things, I want to pick up guns

#

and shoot them

turbid heart
#

and worse come to worst, break it down and google individual features

gilded rover
#

ohk

dusky wagon
snow willow
dusky wagon
#

With the player

snow willow
#

Yes but how

#

be specific

#

physics joints?

#

Moving a rigidbody with forces?

dusky wagon
#

Second one

#

The rigid body of the player gets moved with forces

worn gate
#

I'm trying to make it so when I click on the object it casts a 2d raycast up until it touches something and switch position to said thing - 0.7.
So far clicking does nothing.

public class SpikeBehaviour : MonoBehaviour
{
    public bool SwitchedUp;
    private void OnMouseDown()
    {
        RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, Vector2.up);
        if (hit.collider.gameObject.CompareTag("Switchable")) 
        {
            Debug.Log("Switched?");
            gameObject.transform.position = new Vector2(gameObject.transform.position.x,
            hit.collider.gameObject.transform.position.y - 0.7f);
        }
    }
}

Can I get any help? I'm confused

snow willow
worn gate
#

Yes

snow willow
#

Ok then I guess the raycast just isn't hitting anything

worn gate
#

uh it's a simple isometric diamond

#

scale 1, 3

snow willow
#

where is the pivot of the sprite? (i.e., where is transform.position

#

maybe it's not centered so the ray isn't exactly where you expect it to be?

#

What are you expecting the raycast to hit that it is not hitting?

worn gate
#

here's the scene

#

I just want the diamond's raycast to hit the ceiling

snow willow
#

so "Switched" is not logging?

worn gate
#

sprite's position is 0, -3.8

#

no I don't think so

silver walrus
#

Can I get some help please?

dense flame
#

When it’s on air you should multiply input by airSpeed instead of moveSpeed

worn gate
#

Can anyone help me with my raycasting issues?

hardy heart
#

Hey guys, how to make that player will move to mousePos in NavMesh 2D?

dense flame
#

There is no built-in NavMesh2D

#

If you’re talking about some specific tool you downloaded then say which one it is

hardy heart
#

NavMesh in 2d game

snow willow
#

Just use the mouse position in the world as the navmeshagent destination

worn gate
#

Alright i've completely reworked my code but a new problem arose :

using System.Collections.Generic;
using UnityEngine;

public class SpikeBehaviour : MonoBehaviour
{
    public bool Switchable;
    public GameObject SwitchableObject;

    void Update()
    {
        RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, Vector2.up,        
        Mathf.Infinity);
        if (hit.collider != null)
        {
            if (hit.collider.gameObject.CompareTag("Switchable"))
            {
                Switchable = true;
                SwitchableObject = hit.collider.gameObject;
                Debug.Log("Switchable");
            }
            else 
            {
                Switchable = false;
                SwitchableObject = null;
                Debug.Log("Not Switchable");
            }
        }
    }
    void OnMouseDown()
    {
        if (Switchable == true && SwitchableObject != null)
        {
            Debug.Log("Switched?");
            gameObject.transform.position = new Vector2(gameObject.transform.position.x, 
            SwitchableObject.transform.position.y - 0.7f);
        }
    }
}```
#

Now, in order to make onmousedown work I need a collider for my object

#

but if I put a collider for the object, the raycast doesn't detect the tag anymore

snow willow
worn gate
#

alright i'm gonna try to do that! Sound interesting

snow willow
#

Basically you can add a mask to your raycast that lets it only hit obejcts on certain layers of your choosing

#

so you'd put your "Switchable" objects on a special layer

#

and have your raycast only look for that layer

worn gate
#

Oh ok, thanks

#

i'll try to look it up and figure it out, if I have more issues i'll ask here again I suppose

#

So I essentially change the layer of the object that casts the ray if it has a collider so that it ignores completely that collider and tries to hit the next one?

snow willow
worn gate
#

what do you mean?

snow willow
#

I'm saying put the objects that you want the raycast to be able to hit into special layer(s) that the raycast is looking for with a mask

snow willow
worn gate
#

Oh right, i'm just assuming the GameObject is the source object since the script is attached to it and the starting position is the GameObject, what you're saying makes total sense, thanks.

full oyster
#

I have this problem where I can't get 4 directional movement when making a RPG game. I get 8 directional movement. How do I fix this

snow willow
#

What do you want the behavior to be when the user is pressing two directions at the same time?

full oyster
wet umbra
#

you need to negate other keypresses while the primary one is held down

#

if key down: move and set other keydown conditions to false
if key released: dont move and enable other keydown conditions

radiant wigeon
rocky temple
radiant wigeon
#

yes

rocky temple
#

there's a "freeze rotation" checkbox in rigidbody

radiant wigeon
#

ok

rocky temple
radiant wigeon
#

How would I remove friction again?

#

and how would I let a rigidbody jump while moving horizontally?

radiant wigeon
wet umbra
#

you want to use momentum or have the player control movement while in the air?

wet umbra
#

I think that kind of behavior come naturally, if you can move your character in the ground, it should occur in the air

candid flame
#

Can someone help me out? I added a package called "collections" before going to start animating a 2D character and this just happenned

hollow crown
#

You're going to either need to upgrade or downgrade it to a version that has the Length property

#

they quickly deprecated it and removed it, it's irritating

candid flame
#

sorry for not being an expert in unity but, how exactly can I do that?

hollow crown
#

I'd have to check the changelogs to find out what version has it, it's in there

#

there's a dropdown next to the name in UPM

lean estuary
#

2D animation package was merged with 2D Sprite

#

so having both would conflict

hollow crown
#

I don't think that's the issue, I've had this one specifically

#

it's just Collections being annoying

candid flame
#

pretty much, and you cant just delete the warning in the console

#

pretty irritating so yeah

lean estuary
#

oh yea sorry, not animation that was about IK

candid flame
#

so the main solution is to downgrade the collection´s version right?

hollow crown
#

Downgrade to 0.6.0 or below

lean estuary
#

You can try clearing packages in Library as well

hollow crown
#

You may get away with 0.70, but I am unsure. The changelog has the same deprecation notice on both 0.7.0 and 0.7.1

snow willow
candid flame
#

I also have a collection package in a different project, with the same unity version

#

but without this problem

hollow crown
#

It's a mix of the 2d animation package's version, and the version of collections

#

if you can update the 2d animation package, do that first

candid flame
#

that might be a solution, ill have a lookyes2

hollow crown
#

(it should tell you if it can be upgraded)

candid flame
#

seems you were right, I have to upgrade it to 3.2.9

#

I had it in 3.2.4

hollow crown
#

👍 should fix it

candid flame
#

seems like its working now, almost 10 errors did open all of a sudden, but at least I could delete them this time

#

is it normal that happenned?

lean estuary
#

some errors are one time after upgrading in some cases.

candid flame
#

true

#

but now I have a problem after updating the collections version: it goes when swapping to the sprite editor

lean estuary
#

It could be related to the thing I've mentioned. IK package was merged with Animation (not 2D Sprite like I said originally) So if this was built with version before merge it might have wrong references. Probably should rebuild any IK components so they use merged new package.

candid flame
#

that actually was the problem, I just fixed

willow current
#

Does anyone know how to make a realistic-er jump physics in Unity2D?

#

Like when falling the player has to fall faster than the jump

#

But it takes the same amount of time to jump and fall, from what I see in my character

#

when I want the character to fall back to the ground faster than they jump

snow willow
#

In real life, objects follow a roughly parabolic trajectory and fall at the same speed that they launched from the ground at

#

(not accounting for air resistance)

viral moss
#

Not sure if it's exactly what you want, but the implemention in this video feels pretty natural and it's very simplistic.

https://www.youtube.com/watch?v=7KiK0Aqtmzc

Eliminate the low-gravity feeling of a physics based jump with four lines of code. Actually, just two lines. The other two give you the ability to control jump height based on how long you hold the jump button.

Inspired by the following GDC talk: https://youtu.be/hG9SzQxaCm8

Support Board to Bits on Patreon:
http://patreon.com/boardtobits
Chec...

▶ Play video
snow willow
#

so that doesn't sound particularly "more realistic" to me. But if you want to do it, you can add extra force down while in the air

#

after reaching the pinnacle of the jump

willow current
snow willow
#

Just constant acceleration

willow current
#

ah okay

snow willow
#

as long as you're using a Rigidbody and not doing anythig like setting velocity directly, you should get that

willow current
#

I've only used platforms in my projects so I don't see the accelartion alot

viral moss
#

If you want it to go harder you could up the gravity scale the longer the player is off the ground I suppose.

willow current
#

Also is there anyway to code animations through code or do i have to use the animation editor?

snow willow
#

Any field or property the animator can animate can also be modified directly in code

willow current
#

ah okay, thanks

gilded rover
#

yo guys

#

does anyone know a good tutorial for 2d shooting

honest python
#

so I have this ```cs
Lava.transform.localPosition = new Vector3(0f, -10f, 0f);

#

and I know it gets called

#

and there's nothing else controlling its position

#

but it just doesn't work

#

and I know it's not null

grand coral
#

where are you calling that line and what are you trying to achieve

honest python
#

just set the position relative to the camera

#

which is its parent object

grand coral
#

i see

#

and is it moving somewhere you don't want or just not moving at all

honest python
#

not moving at all

#

when I set it as a child of another object it does work tho

#

so

#

solved ig?

grand coral
#

as long as that's ok to not have it as a child of the camera then sure

#

not sure why it wouldn't work as a child of the camera though i've definitely done that before

honest python
#

ye so have I

#
void Death()
    {
        Instantiate(DeathParticle, transform.position, Quaternion.identity);
        Destroy(gameObject);
        StartCoroutine(Reset());
    }

    IEnumerator Reset()
    {
        yield return new WaitForSeconds(1.5f);


        Debug.Log("gone");
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
#

why does this IEnumerator

#

never get called

snow willow
honest python
#

oh

#

right

#

lol

snow willow
#

coroutines will not run on destroyed objects

honest python
#

yes that was silly

blissful inlet
#

Whats the best way to move a character, im using tranform.Tranlate and my character is just crossing the collider, is there another way, without being micro teleportacions?

honest python
#

using rigidbody velocity

abstract olive
#

Rigidbodies have a MovePosition function.

elder minnow
#

I mean, the "best" way is different for different goals you have in mind

blissful inlet
#

i tried using this MovePosition, but then the character stopped being pushed by the gravity

#

void Update()
{
move.x = Input.GetAxisRaw("Horizontal");
move.y = Input.GetAxisRaw("Vertical");

}
private void FixedUpdate()
{
    rb.MovePosition(rb.position + move * moveSpeed * Time.fixedDeltaTime);
}
snow willow
#

everything else is going to basically override all the normal Rigidbody motion in one way or another

#

or simulate your own gravity and use MovePosition

#

but you won't be able to be affected by other outside forces

blissful inlet
#

AddForce worked nice, thanks 🙂

burnt phoenix
#

um can sombody help me with this im trying to make it so that the player flips by rotating but i cant get it
transform.rotation(Quaternion.Euler(180, 0, 0));

dawn trench
#

how do i rotate a sprite without affecting its transform rotation

vagrant nexus
#

you dont really

#

but you can put the sprite on a child gameobject

#

and rotate that instead

dawn trench
#

that'll be a mess

vagrant nexus
#

dont see how

dawn trench
#

i rather just duplicate it and rotate in image editor

vagrant nexus
#

how would the child object be a mess?

dawn trench
#

and use two per sprite

vagrant nexus
#

or wait

#

do you mean flip a sprite?

#

like left or right?

dawn trench
#

i wanna have the least amount of objects possible

#

no

#

that's why i said

#

I'll use two per sprite

#

with flipping

#

i can get the other two

#

but that's terrible

vagrant nexus
#

what is your actual goal, disregarding everything I said

dawn trench
#

so i wanna exactly why does unity not allow it

ruby karma
#

Do you want to rotate the sprite to any possible angle, or just flip it left/right up/down

dawn trench
#

yes any possible angle

vagrant nexus
#

then put it on a child gameobject and rotate it...

dawn trench
#

but i want it to keep moving in the same direction

ruby karma
#

and why do you not want to change the transform?

#

I see

vagrant nexus
#

make the parent move in the direction you want

#

then the child object is rotated how you want

dawn trench
#

but then I'll have to add more components to the code

ruby karma
#

You have two choices :
Tweak your movement.
Use a child object.

vagrant nexus
dawn trench
#

but why tf does unity now allow it what's the reason

#

on i mean

vagrant nexus
#

its like 2 lines of code

dawn trench
#

i have to use that in more 30 lines

#

but yes my method would need more

#

I already have like 6 components that I'm adding publically to the code

#

so is this the right workflow ?

vagrant nexus
#

just add a child object and put it on that, yes

dawn trench
#

having so many public variables

vagrant nexus
#

and yes

#

it does not really matter how many variables you have..

dawn trench
#

is there a way to read them globally

vagrant nexus
#

although they should probably be [SerializeField] private

#

if you dont need them in other classes

#

you can read them if you use GetComponent to get your script

#

then you can access it just as you would a class

dawn trench
#

yes I'm doing that

#

but i mean

#

without making the variables public to drop the sprites on it

#

can i read them from a global container

#

by ID

vagrant nexus
#

oh, yeah, look into ScriptableObjects probably

#

but like

ruby karma
# dawn trench but why tf does unity now allow it what's the reason

Sprites aren't runtime resources, they are assets which shouldn't be modified at runtime. Unity offers a way to do what you want and that is via multiple objects. For it to work as you would expect, it would require a serious amount of change in how SpriteRenderer works.
SpriteRenderer probably generates flipped sprites or something similar prior to game run already 🤷‍♂️

vagrant nexus
#

seems kind of pointless since most of the time since you would just be dragging and dropping them anyway

dawn trench
#

as i said

#

its not really necessary for now

#

i know how to deal with this with no changes

#

just that when i use it later on a much larger scale

#

guess I'll have to learn a lot more

#

probably how to code your own shaders, since that's one way to have full control

#

right ?

vagrant nexus
#

I mean, sort of... over some visual aspects, yes

#

but you dont really have "full control" in unity

#

its a non-open source game engine

dawn trench
#

yes that's why i switched to unreal for 3d

#

but its hard for 2d

#

so I'm using unity for only 2d

dawn trench
vagrant nexus
#

both unreal and unity are 3D engines so

dawn trench
#

but after using for a while i prefer unreal over unity

#

for 3d

vagrant nexus
#

a lot of 2D features are kind of lacking in unity

#

but its not impossible to use

dawn trench
#

yeah there is always a way around it

#

just that few features that should be straight forward

#

aren't present

#

well thanks for replying anyways

late viper
#

there's always godot if you really want full control

dawn trench
#

ummm no I'll stick to this enough bouncing around

#

for now

dusky wagon
#

How would I make my on trigger method only play if certain game object or layer enters the collider?

marsh quail
#

just use an if statement

lament oasis
#

There is no different between OverLapCircleAll and OverLapBoxAll instead of the shape,right?
I mean, they do the samething,right?

distant pecan
dawn trench
#

Yes but I just don't like it so I went with something else

#

Works all fine

distant pecan
distant pecan
#

make sure that your gameobject isn't in the fish layer, otherwise it will detect itself in the collider[] array

bright fjord
# lament oasis

That's probably the case because your Collider isn't the Root GameObject, OverlapBoxAll will give you the Colliders, not the Root GameObject

distant pecan
#

what may be happening in this case is that overlapcircle isn't colliding its own casting object, but overlapbox is

lament oasis
#

as i said, everything i change is the shape to take colider from Circle to Box, nothing else, but it work different like that +_+

lament oasis
#

it already destroy the fish if i use Circle

#

but if i use box, the colider destroy itself, dont know why

dusky wagon
distant pecan
lament oasis
#

maybe UnityEngine is bug, cuz i use if to catch just GameObject have tag ca, but it still catch everything on it

woeful sentinel
#

Unity is not a bug.. Unity is a game engine

#

showing your code may help solving your problem faster

lament oasis
ebon basin
#

Point still stands tho show Ur code lol

honest python
#

my 2D collision detection is not happening every frame

#

I havew like 1200 fps

#

and it still kinda moves into other stuff before snapping to the right position

snow willow
#

it is independent of framerate

honest python
snow willow
#

Project Settings -> Time -> Fixed Timestep

snow willow
#

or decrease it rather 😄

honest python
#

theen will by FixedUpdate time also increase?

snow willow
#

Fixed timestep of .02 -> 50 calls per second
Fixed timestep of .01 -> 100 calls per second

#

etc

honest python
#

I see

worldly leaf
#

howwww

snow willow
#

in this case - OnTriggerEnter2D is inside another one of your functions

#

which means it is a "local function". And Unity will never call it.

worldly leaf
#

@snow willow function in another function?

snow willow
#

you have something like this

#
void Update() {
  void OnTriggerEnter2D(Collider2D collision) {
  }
}```
But it is suppsoed to be like this:
```cs
void Update() {
}

void OnTriggerEnter2D(Collider2D collision) {
}```
worldly leaf
#
using System.Collections.Generic;
using UnityEngine;

public class EnemyMove : MonoBehaviour
{
    public int speed;
    public bool MoveRight = true;

 
    void Update()
    {
        if(MoveRight == true)
        {
            transform.Translate(2 * Time.deltaTime * speed, 0, 0);
            transform.localScale = new Vector2(1, 1);
        }
        else
        {
            transform.Translate(-2 * Time.deltaTime * speed, 0, 0);
            transform.localScale = new Vector2(-1, 1);
        }

        void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.tag == "turn")
            {
                if(MoveRight == true)
                {
                    MoveRight = false;
                }
                else
                {
                    MoveRight = true;
                }
            }
        }

    }
}```
#

@snow willow its all of code

hollow crown
#

the problem is exactly what they stated it is

worldly leaf
#

but the man in vid can run it with same code

hollow crown
#

The code is not the same

snow willow
worldly leaf
#
using System.Collections.Generic;
using UnityEngine;

public class EnemyMove : MonoBehaviour
{
    public int speed;
    public bool MoveRight = true;

 
    void Update()
    {
        if(MoveRight == true)
        {
            transform.Translate(2 * Time.deltaTime * speed, 0, 0);
            transform.localScale = new Vector2(1, 1);
        }
        else
        {
            transform.Translate(-2 * Time.deltaTime * speed, 0, 0);
            transform.localScale = new Vector2(-1, 1);
        }

        
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "turn")
        {
            if (MoveRight == true)
            {
                MoveRight = false;
            }
            else
            {
                MoveRight = true;
            }
        }
    }
}
#

like this?

blissful inlet
#

I created a grappling gun in my game, based in Camera.ScreenToWorldPoint(Input.mousePosition); and using a Line Renderer, but i want to use a layer mask, to just use the gun in specific layers, but i need a function that tells me if in the mouseposition exists an object, and verify its layer, to see if fits the layer entered

#

does someone see a solution to this?

bright fjord
#

Camera.ScreenPointToRay

#

could be the right thing

pine orchid
#

Hi i have a question, am trying to make a leaderboard for my game, i currently have a scoring system for my which saves high scores, i want a leaderboard that stores the top 3 scores.

#

i tried couple of yt videos but they all show leaderboard for online hosting, i just want an offline one

vital frost
#

having a problem where my character dies from a enemy, but it then crashes the game.
I believe it has to do with this part of the script.
Its either that or I'm just dumb and assigned the wrong things in the wrong places.

snow willow
hazy pilot
vital frost
late viper
vital frost
#

ah ok so I need to reload the player or create a function that calls them back?

snow willow
vital frost
#

my camera apparently

snow willow
#

your camera is pointing at the player

#

which is destroyed

#

So then it doesn't know what to do

#

right?

vital frost
#

hm yeah makes sense

#

alright I know how to edit that

vital frost
#

Actually now I'm having trouble doing it
Do I destroy the camera in the same script with the player?
Or destroy it at all?
I'm new to programming sorry about this lol.

vital frost
#

oh so either

vital frost
#

would it be possible to instead have it focus on the respawn point as the player respawns?

snow willow
#

anything is possible

#

you just have to code it

#

like - target = spawnPoint; when the player dies.

vital frost
#

aw ok

#

thanks for the help

#

would I go into the camera or player death script for that

burnt badge
#

whenever i run this code, the print reads false

#

but i dont see how thats possible, since to even get to the print line, the object would have to be in the list, so then why cant it remove it?

late viper
burnt badge
#

the out of range function is a simple check to see if the enemy is outside the range of the tower

subtle vessel
#

that code should throw an exception, I think

#

you're altering the collection inside the loop

late viper
#

oh that makes sense

burnt badge
#

yeah i know right? thats another strange thing

late viper
#

so its not that it's not finding it, its not successfully removing it

burnt badge
#

i see

#

whats the best way to like, remove items from a list after checking each item?

#

like, if the enemy is outside the towers range i want to remove it from the list, but obviously using a foreach on the list would throw an error

subtle vessel
#

in this case, you can iterate through the list backward and safely remove the current item

burnt badge
#

that sounds dope af

late viper
#

idk if it'll let you do that

#

you're still changing the list

burnt badge
#

do you know of another way reo?

subtle vessel
#

for(int i = selectedEnemyList.Count; i > 0; i--) { if(stuff) { selectedEnemyList.RemoveAt(i); } }

#

you're only changing the parts of the collection taht you've already checked, so it is safe

late viper
#

store references to them in another list remove them outside the loop?

burnt badge
#

implimenting now

late viper
#

you can try both and see what works

burnt badge
subtle vessel
#

or you can make a list of items to remove during the loop, then remove them after you've finished looping

#

also, there are probably some off-by-1 errors in my example above. I think it should be RemoveAt(i - 1);

burnt badge
#

yeah i just got thrown the outofbounds, thats probably why

#

no, im still getting an outofbounds, gimme a bit while i figure this out

late viper
#

should be int i = selectedEnemyList.Count - 1 first

#

because you use i in the if check

#

or you can do i - 1 in the if check, whichever works

burnt badge
#

yeah, i implimented that and it works, it removes the item from the list and no errors

#

thanks reo and tach, i appreciate the help!

still tendon
#

i need help

#

@abstract olive i need help

abstract olive
still tendon
#

i go to put the player content into the add component and it says: "the script don't inherit a native class that can manage a script

#

@abstract olive

abstract olive
still tendon
#

oh sorry

arctic cloud
#

Hi, is there anyone who knowss how to change the size of the grid in tile pallete?

hollow rampart
#

Sorry if this is more of a question for #⚛️┃physics , I just joined as I am a bit desperate since I don't really know how to search this problem.

So I have a simple setup of using Addforce in the direction of the mouse, works perfectly until I rub against an edge collider, which then skews some of the momentum causing an odd strafe effect.

Black being the force applied
Red the colliders
and Blue being the momentum after bumping into the wall.

Is it that I don't have an axis contrained maybe?

#

Oh and let me get the script

#

AH, found it out, needed to lock the z-rotation on the Rigidbody

jolly hawk
#

I want to do a mobile game where one tap to screen would perform small part of action and X amount of tapping to screen would perform this task and finish this task. How would I go about this? Any sources how to make this kind of action performance?

dawn trench
#

Bruh tell me a classic snake game where the snake has "bends" isn't "very easy" to code

#

Whatever I've implemented just looks terrible

ruby karma
#

anything curving is not very easy

dawn trench
#

And it teleports too

#

So I have to deal with coordinates where the distance between cells isn't one unit

dawn trench
#

I have like three giant if else chains to deal with it

#

I don't see another way to do it

runic cipher
#

quick question, does tilemap.getTile return the specific tile on the tilemap, or the original tile that the tilemap copy pastes onto every tile?

dense flame
#

I think return the tile that is copy pasted

runic cipher
#

is it possible to get the specific tile?

dense flame
#

I don’t think you can, you need to use the position to change the tile

#

Tilemap are pretty confusing in this cases

runic cipher
#

how exactly would I do that? I'm using a class built ontop of Tile, I'll refer to it as "newTile". newTile has an array of sprites and based on an Int value called "state" chooses a sprite from the array to display. Is it possible to access and edit the "state" variable in this case?

subtle vessel
lament oasis
#

If i spawn a gameobject inside a colider, can it trigger OnTriggerEnter2D? xD

dawn trench
#

Coordinates are brain damaging

dawn trench
#

wow i feel stupid i wrote 6 complicated lines for a function that only needed one if statement

restive wedge
#

man im doing something wrong. im trying to make a function that switches animator controllers and keeps the current frame (like megaman when he walks normal and then when he shoots during the walk he retains the current frame he was on during the normal walk). i think im stuck on the end...but i dont know how to give the weight or length values to the new clip info, any ideas?

    {
        AnimatorClipInfo[] animationClip = animator.GetCurrentAnimatorClipInfo(0);
        //int currentFrame = (int)(animationClip[0].weight * (animationClip[0].clip.length * animationClip[0].clip.frameRate));
        var currentWeight = animationClip[0].weight;
        var currentLength = animationClip[0].clip.length;
        var currentFrameRate = animationClip[0].clip.frameRate;

        if (isNormalController)
        {
            animator.runtimeAnimatorController = normalController;
        }
        else
        {
            animator.runtimeAnimatorController = normalAttackController;
        }
        AnimatorClipInfo[] newAnimationClip = animator.GetCurrentAnimatorClipInfo(0);
        newAnimationClip[0].weight = currentWeight;
    }```
compact cave
#

Hi everyone! I'm wanting to save a time as a high score in my game and I made a class for the time. I want to save my current time if its less than my current best time, but unity gives me an error for the line where I check this.

snow willow
#

so it's null

#

and you're trying to read null.min

#

initialize best with some placeholder scores first

#

best = new GameTime(0, 0, 0);

compact cave
#

Ok thank you ill try that

snow willow
#

also I recommend a function on GameTime that simply returns the time as a single long value in milliseconds. Then it will be extremely easy to compare them with a single if statement rather than a long chain of them

compact cave
#

Thanks so much

#

It works now

mild mortar
#

hello, i have a 2d setup going on but whenever i add my main avatar, it doesn't appear on the page properly

#

actually, it doesn't appear at all

#

the outline of its object is present, but the actual contents within that are empty

red glacier
#

I was wondering how I could make my grappling hook work with moving rigidbodies, can anybody help me?

mortal ginkgo
#

If anyone Knows how to make soft bodies work with bones in unity then please hit me up in my dms so we can talk about it

mortal ginkgo
subtle vessel
# red glacier I was wondering how I could make my grappling hook work with moving rigidbodies,...

There are a million different ways to do this. What exactly do you want your grappling hook to do?
If you want most of the work done by Unity rather than writing it all in code, 2D joints might work for you. https://docs.unity3d.com/Manual/Joints2D.html
When the grappling hook hits, attach the objects with a SpringJoint2D maybe and let the join drag your objects together. Just one example of how you might approach it.

red glacier
#

I mean my whole grappling hook works, just doesn't work with rigid bodies. whenever I do it with rigid bodies it connects to where it last was then if it moves the rope doesn't move with it.

if you want to look at the code its all explained and shown in this video: https://youtu.be/dnNCVcVS6uw

Thanks!

Link to the project:https://github.com/PizzaDestroyerX/Unity-Mehcnaics
Link to the code: https://bitbucket.org/Vespper/grappling-hook/src/master/

In this video we'll create the PERFECT grappling hook for your game. the code is open source, so let's all make this already pretty good grappling hook to an amazing one.

Thank you everyone for 100 ...

▶ Play video
runic cipher
#

Hi, I made a BFS search algorithm that uses a distance value as a check. Is it possible to reduce the amount of memory needed? Since I'm using essentially 3 lists in the algorithm. Thanks!

List<Node> getTilesInCircularDistance(Node origin, float distance)
    {
        //find a way to see if it is possible to reduce the number of needed memory

        //BFS search using distance from origin as completion requirement
        Queue<Node> BFSQueue = new Queue<Node>();
        HashSet<Node> discoveredNodes = new HashSet<Node>();
        List<Node> passedNodes = new List<Node>();

        discoveredNodes.Add(origin);
        BFSQueue.Enqueue(origin);
        while(BFSQueue.Count > 0)
        {
            Node currentNode = BFSQueue.Dequeue();
              //getSquareLinearGridDistance returns the squared distance between 2 nodes on the grid
            if(grid.getSquareLinearGridDistance(currentNode, origin) > distance * distance)
            {
                //Node is out of Distance
                continue;
            }
            else
            {
                passedNodes.Add(currentNode);
            }
            foreach (Node neighbour in grid.getGridNeighbours(currentNode))
            {
                if(!discoveredNodes.Contains(neighbour))
                {
                    discoveredNodes.Add(neighbour);
                    BFSQueue.Enqueue(neighbour);
                }    
            }
        }
        return passedNodes;
    }
snow willow
#

I always do BFS with just two collections: the "fringe" queue, and the "already visited" set

#

or I gues - is there a need for "passedNodes"?

#

what is passedNodes doing

#

Oh it's the results?

runic cipher
#

when I outputed discoveredNodes it included some extra Nodes which I'm not very sure about how they got in there, so I added the passedNodes which just checks if the distance is under the wanted distance.

snow willow
#

here's a BFS I wrote recently:

        public void BreadthFirstTraversal(RadialNode root, Action<RadialNode> visit) {
            Queue<RadialNode> fringe = new Queue<RadialNode>();
            fringe.Enqueue(root);

            while (fringe.Count > 0) {
                RadialNode current = fringe.Dequeue();
                foreach (var child in current) {
                    fringe.Enqueue(child);
                }

                visit(current);
            }
        }```
#

but this is for a tree

#

so I don't have an "already visited" list

#

because trees are one-way

runic cipher
#

if I included a parent-child system for each Node under the getNeighbour function would that let it work in a similar way?

snow willow
#

it's pretty similar to yours so maybe you have an issue with your getGridNeighbours function?

runic cipher
#

the getGridNeighbours function just returns a reference to the 8 nodes that surround the argument Node

#

Actually I think I might have a solution here let me try something.

snow willow
#

oh

#

I think... maybe it's better to do the discoveredNodes check when you are visiting a node (first thing in the while loop) instead of doing the check as you decide whether to add the neighbor to the queue or not?

runic cipher
#

the discoveredNodes is meant to keep track of which ones are already added, so that I don't check a node twice. Would that logic still apply with that solution?

#

Also my attempted solution froze the game and outputted 30 errors per second. Sounds about par for the course, heh

subtle vessel
#

are you just trying to get all nodes within a certain radius of the center?

runic cipher
#

yes

subtle vessel
#

a hacky solution that I've used before is to just loop over a square and check whether each node is within the distance

runic cipher
#

An issue with that is that I plan to use this in a "tactics style" game, like XCOM or Wargroove, where the environment can have an effect on the traversable nodes, if I used that method then it would be harder to implement the environmental effects.

#

Thanks for the suggestion, though. I think I can find use cases for that method.

subtle vessel
#

mmm, so you're essentially looking for Dijkstra's out to a certain radius

runic cipher
#

isn't BFS and Dijkstra for different use cases?

snow willow
#

Dijkstra is pretty much BFS but with keeping track of travel distance to each node as you traverse the graph

subtle vessel
#

yeah, I guess. I think of Dijkstra's as A* without directionality to it, but I guess there is the sorting of path lengths too

snow willow
#

yeah - and A* is just Djisktra's with a physical heuristic to guess which way to search first 😛

#

they're all part of the same family

runic cipher
#

Forgive me but I still don't understand how Dijkstra will work in this case, isn't it meant to search out to a target Node instead of exploring all possible Nodes?

snow willow
#

all you do is change the conditions for stopping

#

instead of stopping when you hit some target, you stop when you can't find any more nodes that are within your movement budget

hazy pilot
#

Not to ask the obvious question, @runic cipher , but would a non-BFS search be better? IE - just checking every node in your system and adding them to a "found nodes" list if they're within distance^2 (or whatever your logic is there) ? Or are there too many potential candidate nodes

runic cipher
#

I see, do you have a piece of documentation I can refer to?

snow willow
#

I wouldn't be pointing you to anything except the google result for dijkstra's algoirthm.

#

Most of what I know I remember from college

hazy pilot
#

if (thisNode.distanceFromOrigin < maxDistance) foundNodes.Add(thisNode); etc

runic cipher
#

I want to keep the system modular so that it can scale regardless of the map size, but I expect the maps to be about ~50x50 at maximum. I just followed BFS since it seemed logical.

hazy pilot
#

oh if they're 50x50 i wouldn't worry about performance or memory, tbh

#

I mean as long as you're not doing something too boneheaded like searching for those nodes every update() call 🙂

runic cipher
#

that was definitely not what I tried first I swear

hazy pilot
#

sometimes the easiest-to-program solution is the best one, until you run into problems, then you optimize those functions

snow willow
hazy pilot
#

i think in general it is worth keeping your update() calls minimal, and even if you need to figure out this set of nodes "often" you could at least do it every second or less and it would probably still be invisible to the user

snow willow
#

although the entry under that for "using a priority queue" is the more efficient method

hazy pilot
#

i like keeping my renderer classes with the update() commented out entirely

#
    /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UNITY FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
    #region UNITY FUNCTIONS
    private void Awake() 
    {
        LocalAssert();
        Player.OnPlayerUpdated += UpdateScreen;
    }
    private void Start() 
    {
        UpdateScreen();
    }
    //public void Init() {}
    //private void Update() {}
    private void OnDestroy() 
    {
        Player.OnPlayerUpdated -= UpdateScreen;
    }

my typical "render" screens

#

actually better example

#

so the screen only "does work" when it needs to

#

not exactly the same as your problem but transferable concept - you would only update your list of nodes-of-interest when you need to.. perhaps every 5-10 seconds, or every time someone traverses a node, or whatever makes sense for your application

#

(and you can always work on optimizing FindNodes() or whatever when you're tired of working on real work) 🙂

runic cipher
#

I see, I guess I still have a lot to learn regarding programming hehe

hazy pilot
#

don't we all

#

i think honestly .. don't worry about optimizations until you have FPS or out-of-memory errors

runic cipher
#

Thanks for all your help everyone! I really appreciate it ⊂( ´ ▽ ` )⊃

hazy pilot
#

you might spend a whole bunch of time optimizing your code and then finding out that it runs in 0.001 sec anyway

runic cipher
hazy pilot
#

hehe

snow willow
#

honestly djikstra's isn't that hard but I might be biased having literally learned it in school

hazy pilot
#

little tip... you will 🤮 when you look at your own old code no matter how hard you try

snow willow
#

so ymmv ¯_(ツ)_/¯

hazy pilot
#

i have a little bucket next to my desk specifically for that reason

subtle vessel
#

I gotta get me one of those

runic cipher
#

I don't have a bucket but I have a cup of milk tea that I drink whenever I feel grossed out by my code

#

the sugar helps dampen the disappointment

snow willow
#

yum

runic cipher
#

It also serves as a good indicator for when I need to take a different perspective to the code. If half the cup is empty within 10 minutes then I know something is definitely wrong, although my weighting scale doesn't really think this is an optimal solution

fallen flicker
#

Yes but looking at old code can be a good thing because you get to see how far you've come 😉

hybrid bane
#

hello, so i've been having an issue for a few months now, but i haven't figured it out or received any help yet. if anybody knows what is causing this, i would greatly appreciate help. the problem is that whenever i go into the skinning editor to rig my character, it shows up with these boxes around the sprites. when i try to draw bones onto it, i have to double click a box first and then can only draw bones onto that one section of the sprite.

this isnt how it works in any of the tutorials i have watched, and despite me importing all the needed packages, i still seem to have this issue. please help
https://cdn.discordapp.com/attachments/401076282869415946/852681199008350208/unknown.png

runic cipher
#

Hello it's me again, not sure if it's a coding or more of visualisation question, but it's regarding my previous question. my previous example used BFS to get Nodes within a certain distance from an origin Node, this instance used the pure euclidean distance from a tested Node to the origin Node to see if it's out of range. In this scenario(using pure euclidean distance), is it impossible to use a movement penalty system in the calculations? Since movement penalties in algorithms like this take the form of a "cost" calculated as a Node is checked as a child of another node, which is not shown when taking pure euclidean distance between 2 Nodes.

#

Nevermind, I just answered my own question.

still tendon
#

how do i make my bullet move in the direction it's facing?

turbid heart
turbid heart
still tendon
turbid heart
#

okay, where do you decide whether it's facing left or right?

still tendon
#

in my character controller

still tendon
turbid heart
#

okay, I guess you can create a isFacingRight boolean for your Bullet, and set it when your player fires a bullet? @still tendon

still tendon
#

okay i'll try that

still tendon
subtle vessel
worldly leaf
#

Enemy is patrolling but i want to if enemy will turn, enemy will wait for seconds, after than he will turn and go. Any idea?

turbid heart
#

do you have any errors? I'm not sure, but it looks like your visual studio isn't set up properly yet

topaz dawn
#

You mean the collider?

wide ginkgo
#

Can you show source image?

turbid heart
#

it can be png

wide ginkgo
#

PSD is fine, can you screenshot it when it's open in PS?

#

Yeah understandable. Easiest fix would be to trim the image and remove all empty space. But it might be worth to show you how to fix it in Unity as well.

#

So in Photoshop you'd just Image -> Trim.

worldly leaf
#

no errors

wide ginkgo
#

In Unity you'd select your sprite asset. Then click Sprite Editor. In the editor you can drag the edges to make it smaller. Then click Apply in top right.

#

@still tendon Sorry I completely mixed two things up. If you actually want a smaller sprite you first have to select your Sprite asset. Then make sure Sprite Mode is Multiple. Open the sprite editor, drag a box around your sprite, and hit Apply.

#

When you've done that you should now have a separate sprite in your sprite asset, use that one. Just click the arrow next to it.

turbid heart
worldly leaf
#

@turbid heart i fixed it thanks

livid walrus
#

Hey guys i have a problem, I am trying to create a 2d labyrinth game but i dont know how to fit my game to multiple screen sizes. Thanks for your help in advance

radiant wigeon
#

Do I add a physics material to the player sprite, the ground sprite, or both?

radiant wigeon
#

ok

hybrid bane
#

hello, so i've been having an issue for a few months now, but i haven't figured it out or received any help yet. if anybody knows what is causing this, i would greatly appreciate help. the problem is that whenever i go into the skinning editor to rig my character, it shows up with these boxes around the sprites. when i try to draw bones onto it, i have to double click a box first and then can only draw bones onto that one section of the sprite.

this isnt how it works in any of the tutorials i have watched, and despite me importing all the needed packages, i still seem to have this issue. please help
https://cdn.discordapp.com/attachments/401076282869415946/852681199008350208/unknown.png

mortal ginkgo
#

does anyone knows why this is happening and a way to solve it

(the two collisions are inside of eachother and you can not move when this is happening), both are not triggers

snow willow
#

the brown thing and the red thing?

mortal ginkgo
#

no the colision on the light brown thing and the bowl/brown thing

radiant wigeon
#

Im trying to make it when the player touches a block something happens

I have this code:

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

public class Player : MonoBehaviour {

    float horizonalMovment;
    Rigidbody2D rigidBody;

    void Start() {
        rigidBody = GetComponent<Rigidbody2D>();
    }

    void Update() {
        horizonalMovment = Input.GetAxis("Horizontal");
    }

    void FixedUpdate() {
        rigidBody.velocity = new Vector2(horizonalMovment * 5f, rigidBody.velocity.y);

        if (Input.GetButton("Jump")) {
            rigidBody.velocity = new Vector2(rigidBody.velocity.x, 8f);
        }
    }

    void OnTriggerEnter(Collider other) {
        if (other.gameObject.layer == 6) {
            Debug.Log("test");
        }
    }
}

But nothing happens when I touch the block, I just go through it

knotty barn
#

Is the Trigger called at all? Where is the trigger collider, on the player object?

snow willow
snow willow
snow willow
#

use the 2D one

#

void OnTriggerEnter2D(Collider2D other)

radiant wigeon
#

ok

#

It works but now how would I make it set the player back to the level start?

dusky wagon
#

Is there a way to merge a box and a circle collider into one collider? I had som issues with or being two because sometimes for example a coin counted as two, when both colliders hit it at the same time. I tried making it an edge collider, but it cause even more issues. For example when landing while moving you get teleported a bit

silk sorrel
#

Is it possible to render a tilemap twice, slightly modifying it?

Eg to make the shadow like in the picture

still tendon
#

When I rotate the sprite 180 deg is becomes invisible

#

How to correct it

blissful inlet
#

Set Y to 0 and try rotating in Z to 180

#

I made sprite of a wire (2D), and now im trying to make this sprite look like a real wire, that connects to my character and moves with it and drag across the floor, someone knows?

knotty barn
#

@slim scaffold Don't crosspost.

lime widget
#

quick question. I wrote a coroutine that implements a jump by modifying the Z dimension of my character using transform.position. I also have X and Y movement done through rigidbody.MovePosition. for some reason, I can't seem to move my character in the X/Y dimensions while the character is jumping. input is still working, as I can Debug.Log the vector that the input is generating, and it's printing out values as expected. any ideas?

turbid heart
lime widget
#
    private IEnumerator Jump() {
        float last_height = transform.localPosition.z;
        float max_jump_height = last_height + jump_height;
        while (transform.localPosition.z + (vert_speed * Time.fixedDeltaTime) > max_jump_height) {
            transform.Translate(new Vector3(0, 0, vert_speed * Time.fixedDeltaTime));
            yield return null;
        }
        transform.position = new Vector3(transform.position.x, transform.position.y, max_jump_height);
        jumping = false;
        yield break;
    }
#
    public void OnMove(InputAction.CallbackContext context)
    {
        direction = (Vector3)context.ReadValue<Vector2>();
    }

    void LateralMovementHandler() {
        rigidbody.MovePosition(((direction * speed * Time.fixedDeltaTime) + transform.position));
        sprite.transform.position = rigidbody.transform.position;
    }
#

OnMove is a callback that gets triggered by the Move callback context defined in the Input Action asset

#

LateralMovementHandler is called in FixedUpdate()

#
    public void OnJump(InputAction.CallbackContext context)
    {
        if (!jumping && grounded) {
            jumping = true;
            grounded = false;
            StartCoroutine("Jump");
        }
    }
turbid heart
#

I don’t know how to help because that’s a bit more complex than expected, but hopefully someone else can

lime widget
#

👌 no problem

#

I'm wondering if maybe unity doesn't like it when I call transform.Translate and rigidbody.MovePosition in the same update

turbid heart
#

That sounds plausible

lime widget
#

huh. after changing the rigidbody.MovePosition to transform.Translate it works

#

🤔

#

That's annoying since I need collision detection on lateral movement but not vertical movement

#

Wonder why that's happening...

snow willow
#

transform.Translate just teleports the object directly and bypasses the physics engine entirely

lime widget
#

Yeah I know, that's why I'm using it

#

How does Unity know which one to "do"?

snow willow
#

wdym

lime widget
#

As in, why does it do the Translate, but not the MovePosition

#

Why not the other way around?

#

Or is it UB?

snow willow
#

translate is going to just overwrite anything the rigidbody is doing basically

#

so it doesn't matter if the RB moves somewhere because the Transform is getting teleported

#

also MovePosition doesn't happen until the next physics update happens

#

From your code snippets it's unclear where you're calling it

lime widget
#

Ah I see. Does it get tossed into some sort of queue?

#

I'm calling it from within FixedUpdate

snow willow
#

not a queue

lime widget
#
    void LateralMovementHandler() {
        transform.Translate(direction * speed * Time.fixedDeltaTime);
        // rigidbody.MovePosition(((direction * speed * Time.fixedDeltaTime) + transform.position));
        sprite.transform.position = rigidbody.transform.position;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        LateralMovementHandler();
        CheckGrounded();
    }
snow willow
#

if you call MovePosition twice between physics updates, it just uses the most recent position you called it with

#

it overwrites

lime widget
#

ah I would think it would aggregate

snow willow
#

it does not

lime widget
#

I see. Is it the same case with transform.Translate?

#

As in, if I have two translates it uses the "last"one

snow willow
#

no

#

translate happens immediately

lime widget
#

hmm, so would it work if I did translate and then rb.MovePosition?

#

I'm assuming Coroutines are evaluated after everything else in the script is, which is why I'm not seeing the rb.MovePosition

ebon galleon
#

Anyone know much about IK Managers? Mine seems to work fine when animating but when running the game the sprite legs (the bones I used the IK Manager on and other parts, but both being LimbSolver2D and FabrikSolver2D) are just acting like moving sticks instead of bendable legs. Bones themselves seem to work fine though.
Please if anyone has any suggestions I'm more than happy to try them

vital frost
#

I wanna make my camera snap to the respawn point after you die and then snap back to the player
how would I go about that?

ebon galleon
vital frost
#

hm k ill mess around with it

vital frost
#

Yeah idk what the hell im doing lol

#

I dont know how I would go about this still or what functions I would need to use

still tendon
#

Alright folks I have a problem with the linerenderer not showing up on top of the scene

#

This is playmode