#๐Ÿ–ผ๏ธโ”ƒ2d-tools

1 messages ยท Page 46 of 1

full oriole
#

the attack on the right side is an animation

#

with a trigger called attack

carmine stag
#

ok

full oriole
#

so in your case when you press space

carmine stag
#

but how do i put it in the code?

bronze sundial
#

hello, so the combat in my game is melee, and i want to have my script check for enemies entering the sword hitbox as long as the animation is playing (because my melee is a dash attack, i sometimes will dash into an enemy mid swing) but i run into the problem that damage and knockback gets applied once per frame, since its checking as long as the animation is playing. is there a way that once i apply damage to an enemy, i cannot apply any more damage until the animation ends / i swing again?

here is the important code:

void Update()
    {
        if ((this.animator.GetCurrentAnimatorStateInfo(0).IsName("swordSlash")) || (this.animator.GetCurrentAnimatorStateInfo(0).IsName("swordSlash2")) || (this.animator.GetCurrentAnimatorStateInfo(0).IsName("swordSlash3")))
        {
            Attack();
        }
    }

    void Attack()
    {
        // Detect enemies in range of attack
        Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(SwordHitbox.position, attackRange, enemyLayers);

        // Apply "damage" to enemy(s)
        foreach (Collider2D enemy in hitEnemies)
        {
            enemy.GetComponent<slimeHP>().TakeDamage(attackDamage);
        }

    }
carmine stag
full oriole
bronze sundial
# carmine stag but how do i put it in the code?
if (Input.GetButtonDown("Jump") && isGrounded == true && (animator.GetBool("playerDead") == false))
        {
            Jump();
        }

the function:

void Jump()
    {
        isGrounded = false;
        animator.SetBool("isJumping", true);
        animator.SetBool("isCrouching", false);
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
        if(animator.GetBool("shiftHeld") == true)
        {
            moveSpeed = 3f;
        }
        else
        {
            moveSpeed = 2;
        }
    }
#

some of that is unneeded, but just to give you an idea

#

thats the code for my game

bronze sundial
#

use the input.getbuttondown for whatever key you use for jump, and in the function, use animator.SetBool("isJumping", true)

#

theres a video that brackeys made on it

carmine stag
bronze sundial
#

what part doesnt work

full oriole
#

I think the problem with his animation kit

full oriole
#

if i remember correctly it doesnt have a "Freefall" jump state

#

Whereas, in brackeys video it does right?

bronze sundial
# carmine stag https://vimeo.com/548528248

make sure "loop time" is turned off for your jump animation in the inspector, you also need a script to check when your character is on the ground, to cancel the jump animation

carmine stag
bronze sundial
#

gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
this is how you make him jump

bronze sundial
#

you have no exit condition for jump in your animator

carmine stag
bronze sundial
#

do you have a script that checks if you are on the ground

carmine stag
#

@bronze sundial any ideas?

bronze sundial
#

inside the animator tab, right click on jump and make a transition from jump to idle / walking

#

and the transition condition from jump to idle / walk should be "isGrounded == true". you may need to make a new parameter and set it to true / false in your code

#

when jumping, isGrounded == false. when not jumping, isGrounded == true

full oriole
#

he has that already with the "isJumping bool"

carmine stag
#

this is how it looks now

carmine stag
#

@bronze sundial any ideas?

bronze sundial
#

skip to 4:19 for jump

carmine stag
#

@bronze sundial where in my code should I add this?

carmine stag
vital frost
#

Hey all
I've been trying out bolt and i have ran into a problem with my player movement. that being he doesn't move
I believe it has to do with the velocity application part.

snow willow
#

you're calling GetPointVelocity at the end which... is probably not what you want

vital frost
#

ah I see

vital frost
#

wow it was really simple
I just typed in the wrong thing
thanks for the help

dreamy fractal
#

i'm trying to use a overlapcircle to check if the player is touching the ground, but it never returns true, what am i doing wrong?, the groundLayer is a layermask and is declared above, and set in the engine

       bool grounded = Physics2D.OverlapCircle(playerpos, 1, groundLayer);
        //handle gravity
        if (grounded)
        {
            UnityEngine.Debug.Log("Touching");
        }
#

please @ me

snow willow
#

it would come down to the rest:

  • where playerPos is
  • what groundLayer is set to
  • what layers everything is on
dreamy fractal
#

the player is on it's own layer, and the ground layer is set to 3

snow willow
dreamy fractal
#

ok, one second please

#

the code for making the layermask is
public LayerMask groundLayer;

snow willow
#

yep

#

that looks fine

#

assuming the ground parts of your game are on that layer

dreamy fractal
#

yeah they are

snow willow
#

then the last thing to check is - how you are assigning playerpos

#

Are you giving that any value in your script at any point?

dreamy fractal
#

yeah

#

it's in a vector2,

#

and i forgot to assign it

#

wow

#

thanks

#

ok, it's still not working: playerpos = player.position, @ me

#

i gtg, thanks

vagrant hatch
#

is it possible to use a tilemap as spritemask?

wicked saddle
#

Sure, you can put any components on a tilemap

fickle kiln
#

hi all, how do you change the size of an orthographic camera? I have a canvas which uses screen space-camera as it's render capture mode

burnt badge
#

for some reason the addforce command isnt doing anything

#

the top print reads "(-2.1, 4.6)", while the bottom print prints "(0.0, 0.0)"

#

the object isnt colliding or touching anything

obtuse torrent
#

Is there a way I can make a collision box that has holes in it where certain objects are

snow willow
burnt badge
#

no, dynamic

snow willow
#

is Time.timeScale set to 0?

burnt badge
#

it shouldnt be, ive never touched that

#

also everything else around it moves just fine

snow willow
#

that's a pretty small force

#

try printing:

print(sawbladeRB.velocity.ToString("F8"));
#

it could just be a very small velocity

#

If this is like a "one-off" force, launching the sawblade out of a gun or something, you should generally use ForceMode2D.Impulse or ForceMode2D.VelocityChange

burnt badge
#

that line of print read "(0.00000000, 0.00000000)"

#

and ill try with impulse

#

attaching the impulse parameter to the addforce didnt do anything. right now with testing, im having the sawblade spawn 5 units to the right of the launcher so that it isnt touching anything

#

and visual studios telling me that ForceMode2D doesnt contain a definition for VelocityChange

snow willow
snow willow
burnt badge
#

hmm, well it reads dynamic in the inspector, and none of its parents have rigidbodies

snow willow
#

Try printing:

print($"body type: {sawbladeRB.bodyType.ToString()} isKinematic: {sawbladeRB.isKinematic}");```
#

(note there's a separate IsKinematic field that is not the bodyType field)

#

also check the constraints - is the position frozen?

#

also the Simulated field

burnt badge
#

im not sure i understand, its saying rigidbody2d doesnt contain a definition for "isKinematic"

#

and no, no constraints, and yes it is simulated

snow willow
#

should be there ๐Ÿค”

burnt badge
#

shoot, ill try to fix that, but i have to go right now. ill work on it once im back home, thanks for you help preator.

solemn wraith
#

2d-code, maybe you can help me!
im making a 2d rts game and I want some of my tiles to be resource tiles, ala red alert, where you can path over them but a collector unit can gather it.
Whats an efficent way for the collector to tell which tiles are resources vs just any other tile?

hollow agate
#

How can I change the sprite size in my script?

naive apex
#

How to do this in Unity2D?

reef flare
#

hey

#

i have a rectangle and a square... the rect triggers collision with the square.
but when i slid the square to the rect sideways, it doesnt trigger
but when the square is dropped on the rect it triggers

knotty barn
#

@nimble zenith Don't crosspost.

nimble zenith
#

ah very sorry

fickle kiln
fickle kiln
#

doesn't actually change it when I play it

turbid heart
fickle kiln
#

not doing it in code, just doing it manually

turbid heart
#

okay, and when you change the "size" property, it doesnt change how your game looks, at all?

fickle kiln
#

nope

#

changes it in scene view, not game view

turbid heart
#

it does for me.. can you take a video of your game view when you're changing the size?

fickle kiln
turbid heart
upbeat sinew
#

Hi guys ๐Ÿ™‚ I am looking today to try and get a sprite to move across the screen. I would like a sprite to travel from one tile coordinate to another tiles coordinates, and Ideally I would like to draw a line between the two points.

Would anyone be able to give me any pointers here, if there is something I should be using to animate the sprite that will travel, or even simply how to draw a line between two points on a 2d map, that would be excellent.

I can see a basic way to get things done in my head, get coordinates and move sprite etc, but what with cinemachine and not knowing Unity well I thought I would ask around first

wise nacelle
#

So you just want a sprite to go to 1 coordinate then to another? @upbeat sinew

#

like back and forth?

mossy canyon
#

Hey guys. Old man here, trying to learn some new tricks and playing with Unity. I have made a prefab, "Player" and a prefab "Healthbar". My player script has a private Healthbar healthBar; serialized field. I have "dragged" my healthbar prefab into the player prefab in the unity ui. The player prefab is spawned by my network manager when I start my server. I have added code to my player script, that instatiates the healthbar when the player spawn. I have added a debug.log to my healthbar, and it appears to spawn. However, the healthbar is no where to be seen. Probably a vague question, but any ideas what I might be doing wrong? Or what info I can provide to better explain my problem? ๐Ÿ™‚

little ore
# naive apex How to do this in Unity2D?

This is known as "masking", there's various ways to do it, between UI, Sprites and even Quads. Have a look at each of the various ways masking can be used in Unity, and read up on the pros and cons of each to find the one that's what you need.

abstract olive
mossy canyon
#

@abstract olive It looks like it's positioned above it's parent, then "stretched down"

#

@abstract olive I recreated the prefab. Now it looks like it's directly on its parent - just not visible! I see the border .. and the it looks MASSIVE.. but there is nothing inside the border.

abstract olive
#

Can you screenshot what you're seeing/doing?

mossy canyon
#

@abstract olive https://prnt.sc/12xfzvb . I have spawned a Player object. When I spawn the player object, I instantiate a clone of Healthbar that I am planning on showing beneath my character. As you can see from the screenshot, the border of "Image" is the outmost part of my healthbar, whilst "Fill" is the inner part (a slider that I am adjusting to simulate hitpoints)

Lightshot

Captured with Lightshot

#

Bit hard to make out from the screenshot, but my character is under the circle, in the middle of the screen. So the healthbar is grossly over scaled at the moment.

abstract olive
#

Is this a screenspace canvas?

mossy canyon
#

Yes

#

I was thinking that maybe it shouldn't be .. because I want to use the same bar for other elements in the game as well ..

abstract olive
#

Unless you're doing some world to screenspace conversions, the elements are not going to 'follow' a world object.

#

Try redoing it with a world space canvas, and treat it as a normal 3D object.

mossy canyon
#

Can I update the existing prefab to use world space instead? And can I safely ignore the camera warning ?

abstract olive
#

Should be able to yeah.

#

Change the canvas type, resize, and reposition.

snow willow
#

World space canvas will use Camera.main aka FindObjectWithTag("MainCamera").GetComponent<Camera>() if you don't set anything

#

(e.g. if the warning is showing)

#

You can always pre-empt that by explicitly setting a camera for the canvas yourself

mossy canyon
#

Like ... add a new camera, just for rendering the healthbar? (Sorry, the concept of cameras is new to me)

#

Anyway - changing it to world, it now appears to be position where I would expect it (crack in the middle of the parent), but I still can't see anything rendered. No graphics.

#

Could it simply be that going from a 250 px wide image to less than 32px is simply too small ??

abstract olive
#

If you're using a world space canvas, it shouldn't be resizing. ๐Ÿค”

#

If this is a 2D game, make sure the z-value is within the camera's view. Or if it's a child of the player, set it to 0.

mossy canyon
#

I set the scale to make it fit my game. But maybe I shouldn't be doing that? Maybe all graphics should be the "correct size", since this is 2d only ?
(It is a child of player, and the z is set to 0)

idle kite
#

Hey, is there a way getting a (isometric) tilemap as a 2D array?

vocal nimbus
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
    private bool md;
    // Start is called before the first frame update
    void Start()
    {
        md = false;
    }
    // Update is called once per frame
    void Update()
    {
        if(md){
            Vector2 np = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            transform.position = np;
        }
        
    }
    void OnMouseDown(){
        md = true;
    }
    void OnMouseUp(){
        md = false;
    }
#

really basic. I'm not sure what's going on

#

I'm trying to make it more like seen here

rocky axle
#

@mossy lantern how do I make the boy jump?

mossy lantern
#

bruh

rocky axle
mossy lantern
vocal nimbus
#

I attempted to use Vector2 lerp and movetowards, but that doesnt help either

abstract olive
#

@mossy lantern Don't spam this discord, you already have warnings against you.

#

Is that video from a tutorial or something? Can you not follow what they did?

vocal nimbus
#

that video is from my untiy

#

I found a video that does something similar, but mouse dragging in-game wasnt covered

#

I mean I can keep trying to find videos, just figured it'd be simpler to explain my exact concept on the Official Unity Discord server for tips

#

the first video is from in-game, where the second is me moving it in the scene editor

broken cloak
#

so im making a 2.5d game with a 2d sprite in a 3d world and i want to get him to jump but nothing i try is working, i only want him to go up on the y axis as its an infinite runner sort of game, any help?

mossy canyon
#

bill, if it's a 3d world, don't you want to move him up and down on the z axis? (I'm a total beginner with Unity, so I'm just throwing this out there)

broken cloak
#

no you want to move on the y, z is forward and backwards

broken cloak
#

this is me moving on the z then the y

abstract olive
broken cloak
#

harsh

vocal nimbus
mossy canyon
#

Cheers for that - nice to know ๐Ÿ™‚

vocal nimbus
#

Or just use AddForce method to add force in the upwards direction

broken cloak
#

ive tried using addforce and it didnt work

vocal nimbus
#

what issues did you have?

broken cloak
#

ill show you the script hold on

#

it just didnt move

vocal nimbus
#

yea, please show the script ๐Ÿ™‚

broken cloak
#
void Jump()
    {
        anim.SetBool("Jumping", true);
        rb.AddForce(transform.up * jumpforce);
        canjump = false;
    }
#

the function gets called because the animation changes

#

jumpforce is set to 50 or something

vocal nimbus
#

one sec

broken cloak
#

so i changed it to

rb.AddForce(rb.transform.up * jumpforce, ForceMode.Impulse);
#

and it doesnt work still lol

mossy lantern
broken cloak
#

tbf you were spamming

#

no one likes a spammer

vocal nimbus
#

force is too low apparently

#

also make sure you're using FixedUpdate vs Update

#
    private Rigidbody2D rb;

    private bool jumping;
    private float jf;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        jumping = false;
        jf = 500.0f;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Jump") && !jumping)
        {
            Debug.Log("Jump!");
            jumping = true;
            Jump();
        }
    }

    void Jump()
    {
        rb.AddForce(transform.up * jf);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.name == "Floor")
        {
            jumping = false;
        }
    }
#

I was able to make mine jump on the Y axis using this

#

apparently Update is ok, just not recommended for reasons outside of my current knowledge lol

mossy lantern
vocal nimbus
#

lol after you deleted them

#

nah man, def spamming

broken cloak
#

hold on

#

it still doesnt want to work lol

vocal nimbus
#

can I get a screeny of just the code

#

cant control the gif lol

broken cloak
#

yeah sure

vocal nimbus
#

i would standardize using GetKey and GetKeyDown in your code fyi, behavior is different especially since you're not setting any check for your jumps

Can you see what happens if you're on level ground?

plush coyote
#

when you are doing sudden force such as a jump, use AddForce(someForce, ForceMode.Impulse)

vocal nimbus
#

I'm wondering if you're getting a collision, but that'd be kinda fetched

plush coyote
#

(the forcemode part)

broken cloak
#

what do you mean see what happens when im on level ground?

vocal nimbus
#

instead of an incline

#

But try his method first

#

Otherwise I wonder if theres somethign about the animation? But I dont work with animators enough to help even diagnose if that's an issue

broken cloak
#

ive tried it without the aninamtion

#

and he is on flat ground, the camera just makes it look like an incline

vocal nimbus
#

you dont have any constrains or anything set on their rigidbody?

broken cloak
#

no

vocal nimbus
#

also, you're using rigidbody on your player right? Not rigidbody2D?

broken cloak
#

ive changed to using rigidbody2d now as i thought it was becuase it was a 2d sprite

vocal nimbus
#

lol great timing

broken cloak
#

i was using a 2d rigidbody before tho

#

only just started using it

vocal nimbus
#

make sure the RigidBody in your code matches what you're actually using on the character

#

and there's no colliders above the character in anyway?

#

the code looks like it should give you vertical lift

broken cloak
#

yeah

vocal nimbus
#

I'd lower the 9999999 value in the inspector to 500 though

broken cloak
#

and the rigidbosy maches

vocal nimbus
#

for your script

broken cloak
#

gravity also doesnt effect it

fickle kiln
#

anyone know why grid = FindObjectOfType(Grid); is giving me 'Grid is a type which is not valid in the given context'?

broken cloak
#

so thats something

vocal nimbus
#

not for this issue, just for easier to see

#

wait what? Your character doesnt naturally fall down?

broken cloak
#

no

vocal nimbus
#

Something is constraining your Y value

#

or RigidBody is not using it

#

can I see your components for the actor?

broken cloak
#

sure

#

im gonna try the script with a new gameobject

#

(regular 3d rigidbodies)

vocal nimbus
#

yea, you'll want 3D if you're landing on a 3D object or they wont collide as expected

#

even if it's a sprite it'd be fine

broken cloak
#

code for the basic jumping character

#

yeah, it works on that

#

ahhh

#

wait a min

#

one of my animations changes the y axis

#

wait a sec

#

oh and it works

#

just like magic

vocal nimbus
#

lol glad you got it homie

broken cloak
#

god dammit

#

schoolboy error

fickle kiln
#

anyone know why grid = FindObjectOfType(Grid); is giving me 'Grid is a type which is not valid in the given context'?

snow willow
#

It was because Grid is a type, which wasn't valid in that context ๐Ÿ˜„

fickle kiln
#

bro

#

is Grid not a type?

#

I'm using it as a seprate gameobject

fickle kiln
#

also tried grid = GameObject.Find("Grid");

#

but getting Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Grid'

snow willow
#

Does the code I shared not work? @fickle kiln

snow willow
fickle kiln
#

getting this:

Cannot convert method group 'FindObjectOfType' to non-delegate type 'Grid'. Did you intend to invoke the method?```
snow willow
#

show your code?

#

I'm guessing you didn't put the () at the end like i have

fickle kiln
#

yes that was it ๐Ÿ˜…

#

now to try and fix the actual bug which is that I have some objects I want to snap to a grid and am using this function but it snaps the object to the same place on the screen

    {
        Debug.Log("Pointer up");
        var currentPos = transform.position;
        
        transform.position = new Vector3(Mathf.Round(currentPos.x/grid.cellSize.x),
                             Mathf.Round(currentPos.y/grid.cellSize.x),
                             Mathf.Round(currentPos.z/grid.cellSize.x));       
    }```
#

I'll make a vid

snow willow
#

well first

#

you're dividing all x/y/z by cellSize.x

#

instead of the corresponding component of cellSize for each dimension

#

finally - you need to multiply again by cellSize after rounding

fickle kiln
vocal nimbus
#

Can someone help me with this? Posted earlier but still unable to find a solution. I made this ragdoll and it works how I want in the editor, but not using in-game controls. Will post code in a sec

fickle kiln
#

this is what the code looks like now

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("Pointer up");
        var currentPos = transform.position;

        transform.position = new Vector2(Mathf.Round(currentPos.x /       
        grid.cellSize.x) * grid.cellSize.x,
        Mathf.Round(currentPos.y / grid.cellSize.y) * grid.cellSize.y);
                                  
    }
vocal nimbus
#

I kind of fixed it by changing to FixedUpdate() but now it doesnt follow the mouse as well

#

I identified the issue as a continous force of gravity beign steadily applied.... is there any way to get around this?

#

Ive toyed with disabling gravity while mouse is down, but this doesnt allow hinged appendages to flop around as wanted

snow willow
#

also you should really not be modifying the transform of the rigidbody

#

you should be doing rb.MovePosition - and yes in FixedUpdate

#

modifying the transform directly is why you're getting the crazy jittering

#

so:

  • Move the thing in FixedUpdate
  • Disable gravity on the Rigidbody you're grabbing
  • Move the Rigidbody via Rigidbody.MovePosition, not via the Transform
vocal nimbus
#

Ive done the first two. The appengages gravity are still weighing the object down. I'll try the MovePosition method instead

vocal nimbus
#

I tried LERP, MoveTowards, but didnt find MovePosition()

#

Really appreciate it~

#

Any thoughts on how to clamp it to the mouse? Currently if I move it too fast it'll jiggle through the mouse rather than hard stop when the mouse does

fickle kiln
# fickle kiln ๐Ÿ˜•

any idea what @snow willow any idea what's causing this...I multiplied again like you said and am using the correct components this time

wide remnant
#

How would I combine the velocity of lets say: a spaceship and bullet. The spaceship is moving one direction, and firing a bullet to the side. How would I combine the spaceship's velocity with the bullet's velocity to make the bullet fire realistically?

#
pointDirection = transform.TransformDirection(Vector3.up * speed);
rb.MovePosition(rb.position + playerVelocity + pointDirection * Time.deltaTime);
#

^for the bullet

#

Should I be using AddForce() ?

snow willow
mossy canyon
#

@abstract olive You still around mate ?

wide remnant
#

Thanks! Works perfectly!

mossy canyon
#

Still trying to make a healthbar appear below my "Player" object. The player object spawns nicely, and in the Start() method of Player, I have this:
void Start() { playerRigidBody = GetComponent<Rigidbody2D>(); SimpleHealthBar healthBar = Instantiate(simpleHealthBar, this.transform, false); healthBar.setMaximumHealth(100); healthBar.setHealth(60); healthBar.transform.localScale = new Vector3(0.002f, 0.001f, 0.0f); }
The bar is spawning (I think) where I want.. and it follows its parent .. I just can't see it! If I pause the game and select the clone, I can see the borders.. with nothing inside.

Any ideas?

abstract olive
#

@bold plover No crossposting. There are countless tutorials and guides online. Check YouTube.

bold plover
#

No

abstract olive
#

Also this is an English Discord.

bold plover
#

Porque

#

because*******

abstract olive
#

Because the mods are not going to Google translate everything people say in other languages. Please use English.

bold plover
#

it takes a long time to write on google translate

#

I do not know English

#

is spanish worth? or just english?

abstract olive
#

Unfortunately , English only. Maybe you can find a Spanish community for Unity.

bold plover
#

i don't even speak spanish i'm brazilian ....

#

??

vocal condor
#

If you're posting code, it needs to use the proper code tags.

#

After three attempts you'll likely be temporarily muted.

#

By the bot

snow willow
#

Why are you setting the z scale to 0

mossy canyon
#

@snow willow me ?

#

@snow willow Setting it to a vector2 with no change to the z axis yields no difference

mossy canyon
#

Noticing something here. If I double click my prefab, I can see my healthbar perfectly, and I can work on it. If I drag my prefab into my scene, it's not visible. Same as I am experiencing when spawning the entity. What can be causing that?

#

This is the prefab when I am designing it

#

This is when I have dragged it onto my scene to see if it will paint. Sorry for spam.

turbid heart
mossy canyon
#

Yeah, it's an image

turbid heart
mossy canyon
#

@turbid heart So basically expand the prefab to include a root canvas ..?

turbid heart
#

you can try adding an UI element in your scene, you'll see it automatically creates a canvas

mossy canyon
#

@turbid heart the healthbar is getting added programmatically though. Do I just add a canvas to my player object which parents it then?

turbid heart
#

There needs to be a main canvas, and other canvas can go under it

mossy canyon
#

@turbid heart yea, I instantiate it and child it to my player object. The player object is a sprite,but doesnโ€™t have a canvas atm. I was thinking to add a canvas to the player then ?

turbid heart
#

i dont think you can add canvas to a 2d sprite

#

it has to be empty, or a ui element

#

if you want, you can try attaching a canvas component to your healthbar I guess..

snow willow
#

Z scale should be 1

desert crescent
#

Hey folks. I'm building a 2d melee system and I know of three different ways to create the collision detection. I'm curious what your preferences are, or if anyone knows how AAA games use them?

  1. by using physics2d to raycast or overlapcircle, record collisions then do something
  2. Attaching a collider component to an object, animate it, and turn the collider on/off during animation
  3. attaching collider to empty object over top attack animation and using animator to move/shape the collider

My two cents: People likely all use #1. The second and third option seem to be more physically accurate, with option 2 being less work (Assuming sprites and animations are ready for this method)

ruby karma
#

I think its usually a combination of 1 and 2, but I could be wrong.

tame turret
#

@desert crescent sphere(circle)- and raycasts for ranged and fast moving things (delta-position much bigger than collider-"radius"), colliders parented or following joints with lots of toggle on/off for melee, spells, aoe, ... certainly no deformation of colliders when avoidable. You want to keep iteration of your game feel as simple/quick/fun as possible.

desert crescent
#

You guys are amazing. Thank you!

still tendon
#

For some reason this code seems to be running multiple times when i collide with it how can i make sure it consistently only collides once?

snow willow
#

It will run for each Collider

still tendon
fickle kiln
#

I'm posting this again cos I still haven't found out why this isn't working

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("Pointer up");
        var currentPos = transform.position;

        transform.position = new Vector2(Mathf.Round(currentPos.x / grid.cellSize.x) * grid.cellSize.x,
        Mathf.Round(currentPos.y / grid.cellSize.y) * grid.cellSize.y);
                                  
    }

is snapping everything to (0,0)

tame turret
#

just guessing: cellSize is a vector3, maybe your cellSize.y should be cellSize.z @fickle kiln

snow willow
upbeat sinew
#

@wise nacelle yes I would like to create a 2d projectile I guess, I have found some reference already thank you

sand cargo
#

Is there a way to have objects push each other away? I'm thinking of something like a SpringJoint2D, but with a repulsive force (maybe this can be done with SJs but I haven't seen how).

#

Ideally what I'd want is to have a repulsive force, maybe inverse-square of distance -- or just a spring that pushes rather than pulls.

tame turret
#

basically how you would simulate orbital physics with custom gravitiy vectors between all objects

#

to optimize performance you could first check which objects are in range of each other before calculating n^2 interactions

outer snow
#

I am trying to make a RPG (Enter the gungeon) like room generation, does any one got a good video / source for some information on how to do something like that

lavish breach
#
    void Start()
    {
        Collider2D border = gameObject.GetComponent<BoxCollider2D>();
        border.size = new Vector2(32, 20);
    }```
#

in this example, border.size is seen as invalid. size is not recognized anywhere in intellisense, and it does not compile, despite the documentation stating that it exists

#

Every other property listed on the documentation I can edit, and if it is a 3D collider I can edit the size, but for a 2D collider, this isn't coming up

#

What could I be missing

outer snow
#

um i was talking about the whole thing, like the room generation, and the difrent size consideration in it, somthing like a artical on tthe subject of even better a YT video on it

lavish breach
#

I was asking my own question, not responding to yours. Sorry if it seemed that way.

#

Ah, my mistake. It was because border was of type Collider2D and not BoxCollider2D. Oopsie

outer snow
#

oh, ok : )

sand cargo
#

Fortunately I can avoid the n^2 problem by registering items with a repulsive force between them, which isn't likely to be a lot.

tame turret
#

for N < 10 you can usually ignore quadratic complexity

sand cargo
#

not sure about N < 10, but probably N < 50 anyway

#

and this isn't a super high performance situation

idle kite
#

Heyy ๐Ÿ™‚ questions about tilemaps
I want to change in game the color of a tile and I'm doing it like so:

tilemap.GetTile<Tile>(pos).color = newColor;

Now, for some reason it won't change the color during the game, but I do see that the tiles have changed after I pause lol

  1. How can I make them change in game?
  2. I don't want the actual tile to change color - is there other way of doing it?
tame turret
# sand cargo So, roll my own repulsion? Yeah, that'll work. I was hoping for something built-...

Something like this ```cs

/// <summary>
/// Add me to a scene with Repulsor objects (make sure i'm a singleton)
/// </summary>
public class RepulsorSystem2D : MonoBehaviour
{
    private static List<Repulsor2D> _repulsors = new List<Repulsor2D>();
    public static void Register(Repulsor2D repulsor) => _repulsors.Add(repulsor);
    public static void UnRegister(Repulsor2D repulsor) => _repulsors.Remove(repulsor);

    private void FixedUpdate()
    {
        foreach (Repulsor2D me in _repulsors)
        {
            foreach (Repulsor2D other in _repulsors)
            {
                Vector3 me2other = other.transform.position - me.transform.position; 
                other.Rigidbody.AddForce(me2other * (me.Strength / me2other.sqrMagnitude));
            }
        }
    }
}

/// <summary>
/// Add me to objects that repel/attract each other
/// </summary>
[RequireComponent(typeof(Rigidbody2D))]
public class Repulsor2D : MonoBehaviour
{
    [SerializeField]
    private float strength = 1.0f;
    private Rigidbody2D _rigidbody;
    public Rigidbody2D Rigidbody => _rigidbody;
    public float Strength => strength;

    private void Awake() => _rigidbody = GetComponent<Rigidbody2D>();

    private void OnEnable() => RepulsorSystem2D.Register(this);

    private void OnDisable() => RepulsorSystem2D.UnRegister(this);
}```
sand cargo
#

Thanks @tame turret -- very nice!

tame turret
sand cargo
#

I'm sure it's fiiiiiiine

lyric crag
#

how can i find out in 2d from which direction a object exits the trigger?

#

like i have 2 objects

#

i want to find out if the green object exits from bottom

#

nevermind found a way thanks anyway ๐Ÿ™‚

idle kite
#

Heyy ๐Ÿ™‚
I have a tilemap and I want to display some characters above a tile when it's being clicked.

For some reason, I have an enormous offset. I also question the workflow I went with (created custom TilemapData struct based on the tilemap, listening to it and adding floating sprites to the Grid using CellToWorld):

public void UpdateDancers(TilemapData data, Tilemap tilemap)
{
  foreach (var tile in data.Tiles)
  {
     var worldPos = tilemap.CellToWorld(tile.cell);

      var newDancer = Instantiate(piggy, transform);
      newDancer.transform.position = worldPos;
   }
  }
} 
ebon galleon
#

Hi guys, I have some issue with ledge detection. So the Raycasts work and detect a wall normally, works fine etc. (PlayerLedgeDetect script below) But once I've climbed a ledge/been through the climbing animation every time I face right the Raycasts are showing they're hitting something, but there's nothing there to hit.
On top of this, every time the player isn't grounded, despite the fact that the top Raycast has to be false, it triggers the climbing animation when both Raycasts are true.

The CharacterController2D Script reads the values from the PlayerLedgeDetect script and passes them to a value in the Animator Window:
CharacterController2D Script
https://pastebin.com/drwCCp67
PlayerLedgeDetect Script
https://pastebin.com/UaK4gNH8

I hope it makes sense, thanks

mossy canyon
#

@turbid heart I finally solved my problem ๐Ÿ™‚ I ended up adding a canvas to my healthbar prefab, and now it seems to be working nicely! Set the canvas to world position. Child it to my player and now it's following him around like a good puppy!

turbid heart
mossy canyon
#

Haven't quite figured it out yet, but it's all in the process of learning .. so definitely worth the experience!

opaque swan
#

Is there a way I can check if a player has a bool in a boxcollider trigger?

snow willow
vital frost
#

helloooo
i'm having this problem with my animator where my character dose flip but he gets smaller.

#

heres the code i think needs to be changed

turbid heart
vital frost
#

ooooooohhhhh

#

oops

edgy olive
#

@vital frost you can just multiply localscale.x by -1 to keep the current scale

#

like localScale *= new Vector3(-1f,1f,1f)

#

but then u have to only run that if it changed

#

so might not be worth it

honest summit
#

or maybe using SpriteRenderer.flipX = true instead of scaling X by -1

worldly reef
worldly reef
boreal tinsel
#

This will sure be worth your time, but just as a note, please try to understand the algorithm and code fully before typing it and be sure to comment it so you can change it to what you need in the future, good luck!

boreal tinsel
worldly reef
lost oyster
#

I have a character in a 2D game that i want to make bigger, but when i scale him up as soon an i input anything in the game he goes back to the size he was before, is there anything i can do? im new so sorry if this is a dumb question

narrow fiber
#

we'll probably need to see the script you're using to control the character

lost oyster
#
using System.Collections.Generic;
using UnityEngine;

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

    public Animator anim;

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

    float mx;

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

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

        if (Mathf.Abs(mx) > 0.05f)
        {
            anim.SetBool("isRunning", true);
        }
        else
        {
            anim.SetBool("isRunning", false);
        }

        if (mx > 0f) {
            transform.localScale = new Vector3(1f, 1f, 1f);
        } else if (mx < 0f) {
            transform.localScale = new Vector3(-1f, 1f, 1f);
        }

        anim.SetBool("isGrounded", IsGrounded());
    }

    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)
        {
            return true;
        }
        return false;
    }
}```
lost oyster
#

when i jump the character stays the same, seems to be just when moving left/right he goes back to his original size

narrow fiber
#

1 for sure issue and 1 potential issue:

#

For sure issue:
look at the code:

if (mx > 0f) {
  transform.localScale = new Vector3(1f, 1f, 1f);
} else if (mx < 0f) {
  transform.localScale = new Vector3(-1f, 1f, 1f);
}

Notice here, you're setting the character's scale back to 1.

lost oyster
#

ah yeh

#

sorry im new to unity that was a pretty obvious fix

narrow fiber
#

Potential issue:
If your animation on this character modifies the scale of the transform, that will overwrite the value you set in code.

lost oyster
#

ok i'll change the code and see if it works, ty for the help!

narrow fiber
#

no worries ๐Ÿ™‚

mossy canyon
#

Is it easy to adopt a new set of tiles if I make an isometric tilemap? I.e, if I use some free tile pack first - will it be hard to switch to a different paid pack at a later time ?

harsh imp
#

No, you can mix all tilt as long as they are standard, same ratio size

#

And if they re not, it still tweakable

covert phoenix
#

Hi, i'm having a little problem

#

I have a character with a sword that rotates into mouse aim but when the character moves the sword stops rotating

surreal panther
#

can you send the sworld script

covert phoenix
#

I'm sending it but I think i'm doing something wrong??

#

void FixedUpdate()
{
Rigid.MovePosition(Rigid.position + move * SpeedM * Time.deltaTime);

    Vector2 lookDir = MouseP - Rigid.position;
    float angLook = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
    RigidWp.rotation = angLook;
}
#

That's the character sc the rotation is bound there

#

How do you send the scripts like that?

surreal panther
#

y dont know y usually downlowd the script and then send it

covert phoenix
#

Ah okay

surreal panther
#

to what is the script assigned to

covert phoenix
#

the player

surreal panther
#

you should make the sworld have its own little script that sympli rotates it

covert phoenix
#

Okay i'll try

surreal panther
#

and then make the sworld a player child

#

ill just give you a little script thath does just that wait a bit

covert phoenix
#

It's child already

#

Thanksss

surreal panther
#

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 + -90f);

#

from Blackthorndprod

#

just assign this to the sworld in a FixedUpdate and it should work

#

just make sure the camera is set to orthographic or it wont work

covert phoenix
#

Thank you i'll try

#

It works :)))

surreal panther
#

happy to help

near bay
#

i go into edit in unity and visual studio

#

i dont see a settings option

#

heres my function

#

called here

#

ping me when answering

surreal panther
#

@near bay you need to go inside the edit - project settings - input manager and create the jump input

surreal panther
#

wait a minute

near bay
#

k

surreal panther
#

@near bay Just write up

near bay
#

yes

surreal panther
#

in the positive slot

near bay
#

what is negative?

surreal panther
#

you can leave it emphy

near bay
#

ah

#

ok

surreal panther
#

it's used for movement

near bay
#

ah

surreal panther
#

postive is going to return 1

#

and negative -1

#

here are all the types of imput

near bay
#

still

#

shows same erroe

#

ah

#

i did not use capital letters

#

ty

surreal panther
#

ah ok

desert lotus
#

how do I make coins float up and down in my game

knotty barn
#

Add to position y for a bit and then subtract from position y for a bit ๐Ÿ˜›

#

Animations or animation curves could also be used

desert lotus
knotty barn
#

No

turbid plover
#

Hi, what can I do if snap to grid doesn't work?

#

I tried restarting my pc and it still won't work

#

It works on resizing and rotating

#

But on moving it won't work

snow willow
#

It only works in global

turbid plover
#

I tried after this video on world

#

Still won't work

snow willow
turbid plover
harsh imp
#

these kind of toggle always confuse me
It's displaying global cuz its the current state, or it show global cuz if you click it will set to global thus meaning the current state is local

turbid plover
#

It shows the current state

harsh imp
#

for example the pause play/stop button is the opposite in unity

wide remnant
#

How do I make an object bounce off of a wall, but without using a physics material?

#

Like, if I hit a wall, all my x velocity is flipped.

harsh imp
#

OnCollisionEnter()

wide remnant
#

Smacks face

harsh imp
#

u can also use a string body (idk what's called in unity), and adjust the bounciness

wide remnant
#

Why does if (other.gameObject.name == "Left") Debug.Log(other.gameObject.name);
Always return every collider name it collides with when other is from OnCollisionEnter(Collision2D other)?

snow willow
#

I would expect that to only print "Left"

#

maybe you have another script that's printing other stuff

#

or another line of code

wide remnant
#

More or less it's this debug line

#

Also I'm getting a Possible mistaken empty statement [Assembly-CSharp] csharp(CS0642) [37,44] Warning. idk if its related though.

turbid heart
wide remnant
#

oh-

turbid heart
#

You should be getting an error message in the console.. not a warning

near bay
#

Yea

#

Shud be a error

#

Warnings will still run the code

#

Error will not

snow willow
#

and that's not a compile error - it just makes your if statement be pointless basically

#

the only thing that is currently conditional behind the if is the empty statement that is terminated by the semicolon ๐Ÿ˜„

#

the warning is telling you exactly that

wide remnant
#

mhm... Works now, but only if I switch everything to triggers, but that's fine for my purpose.

clear halo
#

Hi ppl ๐Ÿ™‚ Iยดm trying to recreate the mario nes world 1-1 for learning, so i want to achieve that when my playerยดs movement move the camera to the right (when enter in the soft zone of cinemachine and move the camera to right), the player canยดt return to the left bound screen. I look for it in internet but I donยดt know the correct way. I think that put a boxcollider2d as cameraยดs child is not efficient no? (sorry for my english)

snow willow
#

there's nothing particularly ineffecient about it - I would just suggest that you give the collider object a Kinematic Rigidbody2D as well

#

as you should do for any collider that you intend to move

clear halo
#

oh thanks ๐Ÿ™‚ i would like to improve in Unity2d because i want to work in it, I learnt the basic in Unitylearn web and read some books but I donยดt know where to find solutions to my

#

*to some problems when i canยดt find a solution in google, so here is the correct place? I would like to learn more complex concepts

still tendon
#

Assets\arm_follow.cs(27,80): error CS1513: } expected

#

What does this mean?

snow willow
still tendon
#

oh thanks

#

wait why doesn't visual studio show lines

#

and numbers

still tendon
#

Vector3 targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition))

#

I'm not too sure where i need a

#

}

snow willow
#

Impossible to know just looking at the one line

#

you most likely just have mismatched braces

snow willow
still tendon
#

ooh

#

Ty

timber bramble
#

question

#

what's wrong with this code here?

hollow crown
#

GameObjectsWithTag

#

you cannot a transform from a plural group of things

#

get one, or loop over the collection

timber bramble
#

ah thanks

marsh oar
#

Hello, does anyone have a mobile 2D jump script? Thx

knotty barn
#

How you do jumping depends on your existing character controller. You'll probably find better resources if you separate the input method from the functionality

silent warren
#

So guys I have:
โ€ข A Player Prefab w/ a 2D Character Controller attached
โ€ข An Empty Game Object child that contains a BoxCollider2D trigger that's responsible for detecting the ground.

Whenever the BoxCollider2D Trigger touches ground, the player begins descending very slowly. Should i be scouring my code for a solution or is that some kinda issue with Unity's Collision detection?

silent warren
#
        if(isGrounded && !isOnSlope && !isJumping)
        {
            newVelocity.Set(xInput * walkSpeed, 0);
            player.velocity = newVelocity;
        }
        else if (isGrounded && isOnSlope && !isJumping)
        {
            newVelocity.Set(walkSpeed * slopeNormalPerp.x * -xInput, walkSpeed * slopeNormalPerp.y * -xInput);
            player.velocity = newVelocity;
        }
        else if (!isGrounded)
        {
            newVelocity.Set(xInput * walkSpeed, player.velocity.y);
            player.velocity = newVelocity;
        }
#

the only instance where ground check activates and assigns a velocity

mossy canyon
#

Is it just me, or is the default tilemapcollider pretty inaccurate when used for an isometric map ?

solar oyster
#

https://www.youtube.com/watch?v=TcranVQUQ5U at 10:26 the guy types ''update'' and it gets automatically filled for him, however i dont have this myself, any tips? (im using the latest version of visual studio 2019)

Learn how to make a 2D platformer even if you are a complete beginner. In this episode we're gonna focus on installing Unity and making our player move around and jump.

โ— Unity Hub: https://unity3d.com/get-unity/download
โ— Black Square Sprite: https://www.shareicon.net/data/256x256/2015/11/08/668660_box_512x512.png

Subscribe and turn on the no...

โ–ถ Play video
lean estuary
#

@solar oyster If you don't have intellisense working in VS then you didn't install it properly, make sure it is set in preferences as default one. Full steps are described in the pinned configuration guide in #๐Ÿ’ปโ”ƒcode-beginner

solar oyster
#

what is intellisense? sorry im quite new. Thanks for the answer!

lean estuary
#

What detects and autocompletes Unity scripts (among other things)

solar oyster
#

do i have to click on browse? i selected ''visual studio community 2019 [16.9.4]'' before. is that correct?

lean estuary
#

If that's the one you are using, yes

solar oyster
#

but why doesnt intellisense work properly?

#

do i have to get an extension for vs for that?

solar oyster
#

ty

#

you mean i should click on browse?

#

i also cant find that ''editor attaching'' checkbox

lean estuary
#

if it's not there it's irrelevant

solar oyster
#

okay, but what should i do next? i followed every step correctly

#

i pretty much already did all of them before this

lean estuary
#

next open any script from the editor

solar oyster
#

you mean double click a script in unity to edit? or in vs itself?

lean estuary
#

From Unity Editor

solar oyster
#

this is all i get when i type update? is one of them the one that the guy uses in the video?

#

again sorry for the dumb questions i started yesterday.

lean estuary
#

You are most likely outside of the class. Unity methods are right there in the list.

You should not be starting with random tutorials. You need to get some basic understanding of the Engine and scripting. This is a good place to start. https://learn.unity.com/course/create-with-code

solar oyster
#

tysm!

#

but this is an explanation of how the code works, i need to get intellisense working first. @lean estuary

lean estuary
#

You have intellisense, you are not typing in the correct place. Should follow the course.

solar oyster
#

ok thank you for all your help and have a nice day!

green anchor
#

im making a 2d platforme game. and i want my player to do wall jump. but in every tutorial i've watched they let playet do one way wall jump that means player can jump from just one wall. do you have any idea about how to stop it? here's my codes

still tendon
#

so how can i change color of 2d object in middle of game

still tendon
#

but i also want camera to follow my player but in middle of game when u beat lvl1 camera starts following u how??

surreal panther
abstract olive
modest olive
#

whats a camera following script

surreal panther
modest olive
#

๐Ÿ˜

wide remnant
#

How do I setup box colliders on the edge of my camera's view? I tried to line them up manually but the size changes as I enter fullscreen.

vale sorrel
#

Hi, I need help with programming directional input for my enemy AI, I have it set up but don't know how to get it to work in code I've been trying about 2 hours.

calm valve
#

Hey does anyone know if I can create randomly generated levels from like a text file and then use that as a basis for instantiating objects

#

if so how would I go about doing that

ruby karma
#

which part

snow willow
ruby karma
#

that's a lot of steps

calm valve
#

sorry should of added that

calm valve
snow willow
#

The more normal way to do it would be:

  • randomly create the level
  • save the level to a file
  • load the level from a file
snow willow
# calm valve just all of it tbh, i don't know where to start and where to look for info on it

I mean it's not easy but the high level process is simple to understand:

  • create and position the objects in the level
  • record the type of object, the position, rotation, scale of each object, and any other data about the object in a single object
  • serialize that object (this means convert it to text or binary or whatever)
  • save the serialized data to a file

then...

  • read the file
  • deserailize the contents back to the object that represents the type, position, scale, etc.. about the object
  • instantiate the object in the scene and set its position and other properties based on the data you deserialized
#

Just start with this part:
- create and position the objects in the level

calm valve
#

Damn that is very helpful of you, thanks man, that's way easier to start with than "text make things in position I want"

tawny hollow
#

Hi there, uh, so I'm a complete and utter noob, I've never coded anything before and am having to do a simple platformer for class

https://www.youtube.com/watch?v=QGDeafTx5ug&ab_channel=Blackthornprod

I followed along this tutorial, but I can't get my ground check to work, along with some other more minor issues...

The code is here: https://pastebin.com/QRdtfxNZ

and here's a screenshot, showing even though the character's collided with the ground object the ground check still won't activate...

still tendon
#

guys can someone help me max 1 min about 2d code thx

abstract olive
compact cave
#

Hi everybody! Could anyone please help me? So I'm making a game where the player moves by shooting explosive bullets and the player moves from the explosion. The bullet only explodes if it collides with something, but if I aim in a corner the player gets twice the force of the explosion and I need to fix this.

#

Here is some footage:

elder minnow
#

Is it because you instantiate an explosion on impact and this is creating 2 explosions very near each other?

compact cave
#

I know

#

And here is some code

elder minnow
#

You could change a boolean like canInstantiateExplosion to false at the end of that collision method and wrap everything in a check if(canInstantiateExplosion){}

#

and also add a timer, when the timer ends, you flip the bool back to true, essentially making a small cooldown

compact cave
#

Okay thank you very much my Idea was to count the collisions and if Its 2 then divide the force by 2 but i somehow failed to implement that. Thanks again

elder minnow
#

If you want to remove the cooldown, you can do a distance check, and prevent it if the player is being affected by an explosion that is within a certain distance of another

#

No problems, good luck!

compact cave
#

Now it works just like I wanted thanks

mossy canyon
#

When making a 2d isometric game - is it wrong that a character's rigidbody2d has a gravity scale?

elder minnow
#

Yes, it is wrong. Normally, it should have 0 gravity unless you are doing something quirky.

mossy canyon
#

Nice - ty ๐Ÿ™‚

#

Second question. Rigidbody2d. Should it always be moved by using force or is movebody acceptable ?

snow willow
#

They do different things and you need to just understand how they work and what the consequences of each are and do whatever fits your desired behavior

fast siren
#

why am i only able to have my jump function in my update function

    {   Jump();
        Dash();
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;

    }
    void Jump(){
        if(Input.GetButtonDown("Jump")){
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
    }
    void Dash(){
        if(Input.GetKeyDown(KeyCode.Q)){
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(5f, 0f), ForceMode2D.Impulse);
        }
    }
    
}```
vocal condor
fast siren
#

how do i make it public

vocal condor
#

You likely want to put it outside of that scope

#

Scopes are usually defined with the curly braces.

#

Wait, is it outside if Update already?

#

Just make it public using the public modifier prior to void @fast siren

#

Thought it was a local function sure to a lost of indentation.

fast siren
#

its indented i checked

vocal condor
#

I meant relative to discord ๐Ÿ˜›

#

Just place public in from of the return type void.

#

Wait.

#

Your misplacing a curly brace.

fast siren
#

I NOTICED

#

AAA

#

sorry for wasting your time

vocal condor
#

This is what I'm seeing on my tiny mobile screen: ```
{
Update
{
}
Jump
{
if....
{
Dash
{
}
}
}
}

fast siren
#

lmaoo

vocal parcel
#

I was wondering how I would go about creating a "world save system" similar to how minecraft has worlds that you can choose from after creating one?

#

would i just create multiple save files with different IDs?

vocal condor
#

I'm assuming the world is procedurally generated so using the same seed would always produce the same results (terrain wise). Likely, they save items and clusters discovered by the users along with the seed. What do you mean by id?

vocal parcel
#

Alright so like in JSON you can encapsulate all data being saved into one string basically, what I would do is everytime I saved, I would then save that json using Unity's playerprefs and create another int or string with an id that increments based on the number of saves that there already is. That would act as the "ID" and then on the front end when the player is choosing what world they want to play in, I can assign the playerprefs ID to that button basically

#

That way the world is unique for each world, and the data is unique as well

vocal condor
#

Right, should be fine; definitely need some way to differentiate saved worlds.

vocal parcel
#

Yeah thats what I was thinking I just needed someone to bounce ideas off of. Thanks

still tendon
#

how can i make my object go trought object

abstract olive
#

Don't give it a collider, or set the collider to be a trigger.

still tendon
#

but then my player will fall trough

#

hello how make infinity world system i making game be like growtopia?

abstract olive
#

Lots of code.

green anchor
#

do you have any suggestions about enemy combat? im watching tutorials for 3 hours and i cannot make it work.

white cedar
#

How can I make a boss jumo for platforms like this?

viral plank
#

Guys, Hope you all are fine.

#

One quick question.

#

How many active animation controllers can I have in active scene?

viral plank
#

Then simply, write a simple script and drop on to your boss character gameobject to perform the transitions from one platform to other.

honest summit
tough olive
#

So I'm just trying to do a simple ground check for a player and some how this code always returns true as if it is always colliding with the ground layer.
Is this code wrong?

#

Here's my variables set up. Everything matches up, I just quite understand how to get boxcast to work

snow willow
#

For a grounded check

#

Also the RaycastHit - you need to check if the collider on it is not null

#

if(raycastHit) < not sure what if anything this actually does

#

You want if (raycastHit.collider != null)

tough olive
#

Thanks. It always returns true no matter what though(and i did make sure its not colliding with the player). I'll have to play with it later.

solar oyster
#

sorry if this question sounds dumb, im quite new to unity, but this script basically is for a simple square (player) who can move left and right and can jump, but it can jump while in the air, how do i make it detect it when its grounded?

vocal condor
#

You'll want to lookup tutorials about rigid body and ground detection.

#

There are quite a few ways to approach this and some at a higher cost than others; but more accurate.

solar oyster
#

Thanks!

#

ill try looking it up

onyx flicker
#

hi

#

i'm trying to move a gameobject from one place to another in 1 second

#

but using transform.translate teleports it pretty much

green anchor
#

this is my enemycombat script. but they attack always i want him to attack after 3 seconds where am i doing wrong

#

after first attack attackready set to false but enemy keeps attacking

marsh quail
#

try using one &

#

i think && is a c++ code on declaring and

meager moat
#

any way that i can make an object teleport a fixed distance towards the position of the mouse when pressing a button? not setting the velocity but actually moving it the same fixed distance every time

#

would i use a tangent of the distance i want to to calculate the x and y values to move the object?

#

nvm :)

turbid heart
turbid heart
# green anchor

your CheckInRange is assigning instead of checking equality

green anchor
#

i already done that before

#

thats not the problem i guess

turbid heart
#

do you have any errors in the console? @green anchor

jade cedar
#
 if (grounded == true)
   jumpsLeft = jumpsLeftValue;
#

i have this code im trying to make a basic character controller

#

and everything is working except for the jumpsleft value

turbid heart
jade cedar
#

my bad

#

ill change it real quick

#

how do i make it so that jumpsleft isn't made 0 when the player is in the air

#

because when the player jumps (jumpsLeftValue is 2), jumpsleft turns into 1 for a couple of frames but then is quickly set to 0 without player input

#

wait

#

i think the problem is with the input itself

turbid heart
jade cedar
#
        if (Input.GetKey(KeyCode.Space) && jumpsLeft > 0)
            Jump();
#

im not using the right input type am i

turbid heart
jade cedar
#

sorry

#

i didnt want to block the chat

#

i will go to pastebin and put it there

turbid heart
#

that's why I said use a paste site

jade cedar
#

i know that

turbid heart
#

anyway, I think you mean to use GetKeyDown. You're only wanting to detect the Space key being pressed once, right?

#

GetKey would return true everytime the key is pressed, held down, and released. Which is why it might fire multiple times in a single keystroke

jade cedar
#

i tried that but that totally screwed up the movement

turbid heart
# green anchor

well, try setting it up again. it's clearly not set up properly. either way, that's one error. your code probably hasnt compiled because of that error

jade cedar
turbid heart
jade cedar
#

ohh i see

#

my mistake

turbid heart
#

and I still believe you mean to use GetKeyDown

jade cedar
#

do i just change fixedupdate to update in that case

turbid heart
#

I think that goes for your moveInput too

jade cedar
turbid heart
jade cedar
#

i changed fixedupdate to update and it works now

#

swagger

turbid heart
jade cedar
#

thank you

meager moat
#

so i am making a dash function for a 2d platformer, when i release the mouse button, it will calculate the normalized vector pointing from the origin of the player to where the mouse is on the screen, and then using a delta timer, it will set the velocity of the player to the angle vector * dash speed for the time of the dash, which i have set to 0.075 seconds. i am unsure of why, but i am getting a problem where the distance the player covers whenever they release the mouse button is very inconsistent, sometimes going the intended distance, and occasionally stopping early, does anybody know how to fix something like this?

#

or at least what could be causing the problem with consistency?

turbid heart
meager moat
#

was fixing it up a little, still sloppy as heck but i hope it's readable

#

the only thing that has influence over the player velocity other than this is this line of code, which is at the beginning of my update function

#

body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);

turbid heart
meager moat
#

ah, gotcha

turbid heart
#

so the problem is the distance travelled by the dash is inconsistent?

meager moat
#

yes, when i release the mouse button, it will go one of two distances

#

it may be more but i can only tell that it varies between 2

#

i tested this mainly through setting my mouse to one spot, moving against a wall, and dashing towards the cursor a lot, and it's inconsistent even when the player start position and the mouse position are the same

turbid heart
#

okay.. I'm not sure yet, but why do you set the body.velocity like this in Update?

        body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);

Won't that mess with the velocity you're trying to set in here?

        if (dashing)
        {
            dashTime -= Time.deltaTime;
            // sets body velocity to the angle of the mouse
            body.velocity = angle * dashSpd;
            // stops the dash if the timer gets too low
            if (dashTime <= 0)
            {
                dashing = false;
                body.velocity = Vector2.zero;
            } 
        }
meager moat
#

that was the only thing that is on my radar right now

#

im unsure of how to handle this though ๐Ÿค”
should i hand control back to the player only when the dash is fully done?

turbid heart
#

because I wouldve suspected that maybe your direction vector wasnt normalized, but I can see you did that for angle, and your dashSpd never changes. and your startDashTime never changes too

#

I'm not entirely sure how your game works ๐Ÿ˜… but maybe for this
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
let it only run if dashing is false?

meager moat
#

something like

if (dashing == false){
  body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
}```
#

probably?

turbid heart
#

yep

meager moat
#

er yeah game is just a simple 2d sidescroller as of right now

turbid heart
#

I see. I'm just trying to see if it's just some other code that's changing the velocity of your character

meager moat
#

so left and right are the only 2 ways to move with space being the only vertical movement

#

but yeah ill change that rq and see what happens

#

so unfortunately that was not the problem

turbid heart
meager moat
#

damn that sucks

turbid heart
#

I'll look at it somemore. i'll let you know if i think of anything

meager moat
#

hopefully i can figure it out :/ i even looked to see if it was a collider issue and it doesnt even seem to be that cuz it happens midair too aaaaaaaa

#

aight thanks friendo, means a lot

turbid heart
#

you're sure no other script out there messes with the player's movement?

#

also, humor me and try putting the dashing = true at the end of the if statement it's in. So, after the angle is Normalized. @meager moat

#

oh, and do set the dashTime to 0 when you set dashing to false eh, nvm. shouldnt need to..

meager moat
#

thats my only script so far

#

but ill see what happens

meager moat
turbid heart
#

can you try debug.logging these things in your if(dashing) statement
angle, dashSpd

#

see if there's any inconsistencies, like the angle suddenly not being normalized or something

meager moat
#

ill check

#

if i debug a vector will it return all 3 values?

turbid heart
#

yes

meager moat
#

all is well, none of the values look out of line

#

dash speed doesnt change and the angle vector does not change since im keeping my cursor in place

turbid heart
#

uh, try recreating the inconsistency then see the debug.log..?

meager moat
#

it happened when i was looking at those values

#

and nothing looked out of the ordinary for those 2

turbid heart
#

give me a moment to test out your code on my own XD I'm really curious so I'm going above and beyond haha

meager moat
#

aighty i can get you an idea of the scene im working in

turbid heart
#

yeah, can you show me how you set up your speed and startdashtime?

#

I'll comment out all the jump code since I think they're not relevant

meager moat
#

there are all the values that i think i changed or have as variables

#

dont worry about the pointer field since it's for a different time for me

#

other than those variables, its just 3 squares designed to keep the player in

turbid heart
#

can you try moving this line
body.velocity = angle * dashSpd;
to this if statementInput.GetMouseButtonUp(0)

meager moat
#

yeah

#

no cigar

turbid heart
#

sorry, I really have no clue now @meager moat

meager moat
#

unfortunate

dusty maple
#

How would I be able to parent a rigidbody to another rigidbody on collision? When I use SetParent, the parented rb seems to obstruct movement on the parent rb

snow willow
# dusty maple How would I be able to parent a rigidbody to another rigidbody on collision? Whe...

rigidbodies don't really respect the transform hierarchy - child RBs will still move independently of parents. There's two main options:

  • Make the child RB Kinematic - then it will respect the hierarchy and not interact with the parent
  • Use a Physics Joint (e.g. FixedJoint) to "weld" the two together (without parenting). This will act is if you had physically fastened the two objects together.
dusty maple
snow willow
#

you have to destroy the joint to stop it from influencing the body

dusty maple
#

Oh I see

snow willow
#

unfortunately there is no enable/disable for joints

dusty maple
#

So if I wanted to be able to attach and reattach the object, I'm going to have to keep creating and destroying the component? Wouldn't that lead to performance overhead?

snow willow
#

everything you do has performance overhead

dusty maple
#

Ah well that's unfortunate

#

lol at least this is just a simple game

snow willow
#

for a single joint it will be fine

wide remnant
#

I'm trying to use Vector2.Dot to find how closely something is pointing towards another gameobject.

Vector3 direction = Player.transform.position - transform.position;
Debug.Log(Vector2.Dot(transform.up,direction));```
#

This can output numbers up to nine, but the docs say it ranges from -1 to 1

snow willow
#

it only stays in -1 to 1 for unit vectors

wide remnant
#

How do I normalize it?

snow willow
#

direction.Normalize();

#

or Vector3 direction = (Player.transform.position - transform.position).normalized;

wide remnant
#

Okay thanks. Can you tell me what normalizing it does exactly?

snow willow
#

it makes a vector that is pointing in the same direction but has a length of 1

#

instead of whatever its length was

#

basically:

myVector = myVector / myVector.magnitude;
wide remnant
#

Right...

snow willow
wide remnant
#

๐Ÿ‘Œ

mint onyx
#

Hi

still tendon
#

Can someone help me to make my first 2D Game in Unity with C#?

elder minnow
#

If you have a question just state it

still tendon
#

idk i never did anything in unity. I need a full tutorial to do anything like movement or placing yk

steady haven
wide remnant
still tendon
#

okay i will

meager cobalt
#

So i have a problem here

#

my code is complaining about something i havent been able to fix

#

whats the issue

turbid heart
meager cobalt
#

and that means? Im kinda new to unity and stuff

turbid heart
#

Also, you dont need gameObject.transform. Just transform will do

meager cobalt
#

okay

turbid heart
#

That means youโ€™re trying to use something that hasnโ€™t been assigned to

meager cobalt
#

is this what you mean?

turbid heart
#

Double click the error message and itโ€™ll take you to the line with the problem

meager cobalt
#

thats the line

turbid heart
#

Yes. Thatโ€™s better

abstract olive
#

Is the object actually a child of another?

meager cobalt
#

okay but it still does say the error

turbid heart
#

Then.. does your object have a parent

meager cobalt
#

Yes

#

Im trying to basically do that you cannot fly

#

with spamming spacebar

abstract olive
#

Then are you assigning an object to Cube in your inspector?

turbid heart
#

Show us the hierarchy. Are you sure this is the Grounded script?

abstract olive
#

It's either:

  1. You haven't assigned Cube
  2. Cube isn't a child of another transform

Easy to check, easy to fix.

turbid heart
#

What object is the script attached to

meager cobalt
#

Ground check

#

i just named the thing Cube

turbid heart
abstract olive
#

Sorry, yes. On mobile, just skimmed the code.

meager cobalt
#

like what i want is movement script to disable jump when Ground check's box collider is hitting the ground

#

I mean

#

oops

#

Is enable

#

it

#

So you cannot spam spacebar and fly

turbid heart
#

Can you please debug log transform.parent before you assign to Cube in start

#

Let us know what it prints

meager cobalt
#

and how is that done

turbid heart
#

And if you donโ€™t know how to debug log

#

Google it

meager cobalt
#

unity or Visual studio

turbid heart
#

It prints whatever you put in it to the console where youโ€™re seeing the error too

#

Well, i said in start, so obviously visual studio

meager cobalt
#

okay

turbid heart
#

Just google debug log Unity

meager cobalt
#

ok

still tendon
#

can anyone help me?

meager cobalt
#

the first result is Unity documentation with some code, is it that?

turbid heart
meager cobalt
#

Well

#

I just done find how i would do it

still tendon
#

i am trying to create gravity for my game and everytime i add velocity it marks it as incorrect

turbid heart
turbid heart
meager cobalt
#

so where would i insert Debug.log()

#

i'm just lost now

still tendon
#

what do i do?

turbid heart
meager cobalt
#

Infront or after?

turbid heart
#

I said before you assign to Cube

meager cobalt
turbid heart
#

Yeah, now try that and let me know what it prints. I trust you understood what i meant on where to put it

meager cobalt
#

okay

still tendon
#

what do i do?

sudden knot
#

Check the console and see what the error is

meager cobalt
#

where can i see the debug log?

turbid heart
sudden knot
still tendon
#

ok

meager cobalt
#

says this

sudden knot
#

Im new but Im pretty sure you dont use Debug.Log for a game object

#

Mostly use it for values

turbid heart
# meager cobalt

Okay good. Thatโ€™s how you check the value of things. You can see itโ€™s not null. Now can you try changing your Start to Awake?

meager cobalt
#

ok

#

now its awake

turbid heart
sudden knot
#

Ah so you can use it to check if the gameobject is there

meager cobalt
#

what then

turbid heart
meager cobalt
#

hey sorry

turbid heart
#

Also make sure itโ€™s spelled exactly as Awake

meager cobalt
#

now it doesnt say anything

#

oh wait

turbid heart
meager cobalt
#

I changed "awake" to "Awake" and now it inputs

#

also

turbid heart
#

Well thank goodness i assumed you didnโ€™t type it in correctly the first time then

meager cobalt
#

i dont know if those are related anyway here

turbid heart
#

Again, are you still getting the null ref error?

meager cobalt
#

let me see

turbid heart
#

Did you save your script and press play again?

meager cobalt
turbid heart
#

Why are you telling me this? And what do you mean old. Did you remove it?

meager cobalt
#

no?

#

wait

#

Im not getting any null ref errors

#

Only the debug logs thing it says

#

My script is now (and has been)

turbid heart
#

Oh my goodness ๐Ÿคฆ

meager cobalt
#

yes i am dumb

turbid heart
#

Your words not mine

#

I said just put transform.parent inside the Debug.Log. Whyโ€™d you put your whole assigning line in it? I think that makes it not assign at all.

meager cobalt
#

oh i

#

jeez

#

:| time to make it

#

now

turbid heart
#

Look, just put your old code back, and keep your Start as Awake. Somehow youโ€™re not getting any errors

meager cobalt
#

Okay

turbid heart
#

Iโ€™m done helping

exotic cradle
#

Sorry to interrupt, I have a question. I have a text component in this game object that keeps getting covered by another game object within the object.
How do I make the "1" in front of the yellow counter? I tried changing the yellow disk's z position but to no avail, and I don't see a setting in the Text Component section that could help(?)
And no, I don't want the image component to be on the same game object as the text component. I'm trying to make a system involving a changeable stack of circular counters with a number displaying how many there are.

meager cobalt
#

well

#

ok

#

cannot jump still

#

but however

turbid heart
exotic cradle
sudden knot
turbid heart
meager cobalt
#

i'll just go watch another tutorial and delete this all

turbid heart
#

So since your image is your textโ€™s child, itโ€™s going to be in front of it

sudden knot
turbid heart
#

Just swap it so that the text is the child of the image

exotic cradle
wide remnant
#

Destroyer 1(Clone) needs to use GameObject.Find("Player");
but it can't find it.

snow willow
#

Should work fine (though I would recommend at least FindWithTag instead of Find)

wide remnant
#

Hmm... FindWithTag isn't working either

#

UnassignedReferenceException: The variable Player of Turrent has not been assigned.
You probably need to assign the Player variable of the Turrent script in the inspector.

snow willow
#

They work assuming:

  • The player is named or tagged the same thing you're searching
  • The player exists when you call the function
  • The player object is active when you call the function
#

show code maybe?

wide remnant
#

And yes, the player is in the scene when the game starts, tagged and is active.

#

Only stopped working when the destroyer was instantiated from a gameobject that used DontDestroyOnLoad

#

Hold on...

#

Somethin funky happened... I'm taking a break so somebody else can use this channel

forest portal
#

guys I'm working on a 2d platformer

#

and my pc crashed today

#

and unity won't open the project at all

#

it works normally with other projects

#

except that one

forest portal
#

pls

green anchor
#

im working on 2d platformer game and i have enemy prefab that i want to spawn enemies at random spots in map. i also want them to patrol. i was watching the patrol video and had some issues. i have to make the waypoints as a child object to enemy. if i do that it doesnt work well. any ideas?

viral plank
green anchor
#

if i make waypoints as child objects to enemy i meant that

#

like i want him to move +5 right from his position. i dont want him to go specific position