#πŸ–ΌοΈβ”ƒ2d-tools

1 messages Β· Page 54 of 1

still tendon
#

this bit of code should propell me upwards and to the right when i collide with the tag but it only propells me up ,
do you have any idea why that might happen ?

   void OnCollisionEnter2D(Collision2D coll){

if (coll.gameObject.tag == "spiketagtest"){

health-- ; // decrements by one
lives.text = health.ToString();  // converts int to ui text
rb.velocity = new Vector2 ( 20 , 5 ); //  it should change the x & y velocity but it only changes y 

}
   }
arctic stag
still tendon
arctic stag
still tendon
#

is this valid ?
rb.velocity = new Vector2 ( rb.velocity.x + 20 , 5 );

arctic stag
#

It should be

snow willow
still tendon
#

it is but the x coordinate is not changing at all , , i dont know why that happens

snow willow
#

also you may have some other code overwriting the velocity in a different place

still tendon
#

this is how my movement works is this the wrong way to do it ?

snow willow
#

I don't know, whjat are you trying to accomplish

#

this code will instantly add 20 to the velocity on the x axis and instantly set the y component of velocity to 5. Seems like it would be unnatural in most contexts but it's not "wrong" inherently

still tendon
#

so , i have a spike , i collide with it loose health , this works , also when i collide with it i want it to push me back , this dosent work

#

it does throw mw up

#

but it wont throw me asside

snow willow
#

so that will just overwrite this

still tendon
#

i will look into it thx for the advice

#

i found the problem but it comes with a greater problem

#

the x axis is overwriten by all movement

snow willow
#

mhmm

still tendon
#

is there another method of changing velocity instead of setting i ?

snow willow
#

AddForce

arctic stag
#

You could use the add force function and set it to impulse

snow willow
#

IDK about using Impulse, if it's for something that runs every fixedUpdate you probably want normal Force

#

for a jump or something then yeah

#

but basically - it's the same as setting the velocity just additively

arctic stag
#

This is a push tho isn’t it?

snow willow
#

the way you're doing with y velocity

snow bear
#

Hey guys, I'm trying to create a simple building system for my 2d game.
Is it better to use Tilemaps or roll out my own solution for something like this?

snow willow
#

so idk

arctic stag
#

Well anyway I mean use this for the on trigger interaction

still tendon
#

well now im not sure if the movement is the problem or the spike bounce

#

i think that it would be a better way to use add force to the spike

#

instead of the movement

snow willow
#

It doesn't matter what you do with the spike if you're still overwriting velocity with your movement code

#

they need to work together

still tendon
#

so is using velocity for movement a bad idea in general ? im asking this because this is my first time programing in unity and i want to understand how things work

#

is using velocity for movement bad in general or is it for this special case this is what i am trying to understand

#

idk if i should take a diffrent aproach on the spike or on the movement

snow willow
#

"using velocity" is the only way to move a rigidbody in a physics friendly way. The question is how are you using velocity

#

If you want knockback effects, you can't completely overwrite velocity

#

you need to always account for current velocity when changing the velocity. This means instead of completely overwriting it you only ever add or subtract to the existing velocity

#

This is what AddForce does

#

it adds to the existing velocity value

#

but you can also achieve that by doing things like:

rb.velocity += someVector;
still tendon
#

i think i get it ,when i am using rb.velocity = new vector2 ( rb.velocity.x + 20 , y) , i am not adding to it but i am setting it to

#

and add force actualy adds to the velocity

snow willow
still tendon
#

yes but itsnt rb.velocity.x + 20 overwriting rb.velocity.x ?

snow willow
#

so it's taking it into account

#

literally adding to it

still tendon
#

ok so still related to this , new question

#

my character used to slide a lot

#

so in order to stop it i have written a pice of code wich sets his velocity to 0 when not pressing A or D, and it worked it stopped sliding , was that a bad way to do it ?

snow willow
#

you could also just apply a force in the opposite direction of motion to slow the character down

#

that's how real life does it

#

If you just set it to 0 then you can instantly stop a knockback for example.

still tendon
snow willow
#

that's a pretty good way yes

#

that's how brakes in a car work

still tendon
#

rb.AddForce(-direction, 0); what is the correct way of writing addforce ?

snow willow
#

The current velocity is rb.velocity so you would use the opposite of that direction.
Something like:

float brakingForce = 1f;

void FixedUpdate() {
  if (we should brake) Brake();
}

void Brake() {
  Vector2 currentDirection = rb.velocity.normalized;
  Vector2 brakingDirection = -currentDirection;
  rb.AddForce(brakingDirection * brakingForce);
}```
#

But you might want to only apply this on the x axis for example so something like:

#
void Brake() {
  Vector2 currentDirection = rb.velocity;
  currentDirection.y = 0;
  currentDirection.Normalize();
  
  Vector2 brakingDirection = -currentDirection;
  rb.AddForce(brakingDirection * brakingForce);
}```
still tendon
#

all the hours i slept in the physics class now have come to haunt me πŸ˜†

still tendon
snow willow
#

it normalizes the currentDirection vector

#

same direction, magnitude of 1

steady idol
#

guys

#

how can i add the object behind the npc?

maiden forge
steady idol
#

@maiden forge Jay you there?

maiden forge
#

Yes

steady idol
#

Jayy you know about tile palette?

maiden forge
steady idol
#

i created a player

#

but the tiles go on the player

#

i want the colour to go under the player

maiden forge
#

Select your player/sprite and change his ordering layer to 1.

steady idol
#

pog

#

checking now

#

where?

maiden forge
#

You could also create a sorting layer called player and put it below default so its always on top of any object that is listed in the default sorting layer.

steady idol
#

omg

maiden forge
# steady idol

Should be under spriter renderer in additional settings.

steady idol
#

tyvm

#

worked

#

it was also on default

#

had to make it into

#

the one i made

#

example human

#

else wouldnt have worked

#

tyvm

#

it worked!

maiden forge
#

Yw

still tendon
#

soo.. i did not know what normalizing vectors meant and ive gone to understand what that meant ,

#

so is normalizing vectors kind of like merging 2 vectors into 1 ?

#

this is what i understood and now i am asking to see if its correct

snow willow
#

So you can think of a vector as a "direction" and a "magnitude"

#

it's like an arrow pointing somewhere with a certain length

#

the length is the magnitude

#

a normalized vector is just a vector with length 1

#

so if you have a vector pointing somwwhere and it has length 2

#

normalizing that vector means to make a vector pointing in the same direction, but with length 1 instead

still tendon
#

keeping its direction

snow willow
#

yes

still tendon
#

and what does that help me with ?

snow willow
#

it makes it easy to make a vector with any length you want in a given direction

#

because you can multiply a normalized vector by, for example, 5 and now you have a vector with length 5

#

in the same direction

#

in the case of the code above, you can apply a force in the direction you want with the strength you want

still tendon
#

ok but why would it be a problem if i kept the vector to 7 for example and then multiply it by 2 ? sorry for asking so many questions i do understand that you know a lot better then me and all but i want to clearly understand how this works in order to dorrectly use it

dusty bough
#

@sleek sinew @woeful sentinel You were right! Thanks πŸ˜„
My object's z was properly set to 0, but my Agent's wasn't, so it did rotate the object around.

woeful sentinel
#

I thought we answered that like a decade ago 🀣

dusty bough
#

@woeful sentinel But I was sleeping πŸ˜›

snow willow
#

Β―_(ツ)_/Β―

still tendon
snow willow
#

if it's a rigidbody velocity, then the magnitude of the vector is what you might call the "speed" of the body

#

if it's a force, then it's the strength of the force

#

if it's a position, then it;'s the distance of that position from the origin of the world

still tendon
#

i hope i understood correctly

dusty bough
#

There is a billion different interpretation for the meaning of a Vector's components.

#

You have to think about it when you're in the context, but it's usually "something that has a direction and a magnitude".

still tendon
#

ok so i remade my movement and the player still slides a lot , i tryed increasing it but it only started to stop me at about * 20 amplification , also if i run into a wall it will throw me back so the addforce method might not be the best for my player stopping

flat warren
#

i made my movement like this

#

maybe it can help you

#

just ignore the comments made in my language there

#

and the movement variable is Vector2

still tendon
flat warren
#

Hello, I'm making a 5 slot hotbar into my RPG game, but it just doesn't work. I've tried to make it like a thousand times, but i just can't make it work. Can anyone show me the code for a hotbar?

snow willow
#

you wouldn't be able to drop it into your game

flat warren
#

i just need to know how did you do it

#

like look at it and inspire or idk how else to say it πŸ˜„

still tendon
#
  void Update()
    {
        if (Input.GetKeyDown("space"))
        {

            if (Time.timeSinceLevelLoad > nextFireTime)
            {
                nextFireTime = Time.timeSinceLevelLoad + cooldownTime;

                Debug.Log("space");

                Rigidbody2D bulletInstance;
                bulletInstance = Instantiate(bullet, player.position, player.rotation) as Rigidbody2D;
                bulletInstance.AddForce(player.up * 1000f);

                Destroy(bulletInstance.gameObject, 0.6f);

            }
        }


        transform.position = Vector2.Lerp(pos1, pos2, Mathf.PingPong(Time.time * 0.36f, 1f));
    }

                Destroy(bulletInstance.gameObject, 0.6f);

            }
        }


        transform.position = Vector2.Lerp(pos1, pos2, Mathf.PingPong(Time.time * 0.36f, 1f));
    }
#

hello. this is my shooting code. But it shoots 2 bullets at a time

#

this is because it counts one space bar input as two space bar inputs

#

but why is this?

snow willow
still tendon
#

no

#

i have another easy movement script but that shouldnt be active at this time

snow willow
#

see if it still shoots

still tendon
#

k

desert cargo
#

Is there a way to show the Grid component in the scene view?

#

I made this thing

#

Doesn't seem to have any gizmos?

flat warren
#

i have this code sitting on things that i want to show radius

flat warren
desert cargo
#

Nah but it's all good, I just wrote a grid it's pretty simple.

modest cargo
desert cargo
modest cargo
#

It's not a gizmo and it's not the scene grid
It seems unaffected by object visibility settings and only disappears if I disable the object it's on entirely

#

Oh, the object needs to be selected so it'll show up πŸ€”

sweet swan
bleak field
#

can anyone help me with my game?
i want to get one object but i only know it's coordinates, it is possible?

snow willow
#

Not the Grid

#

Unfortunately

desert cargo
#

That is so silly

#

Also "Grid" seems to add a button on the screen that is "show tile palette" lol

#

Why even make it 3 different components

snow willow
#

Could be wrong but I have a TileMap in a game for that reason, because the grid stopped drawing when I got rid of it

desert cargo
#

I just made my own

#

check dis shit

#

got some numbers in the mix

snow willow
#

I was using hexes and was lazy so I just left the TileMap lol

desert cargo
#

Ah yes, that's a good reason

snow willow
#

Nice numbers πŸ‘

desert cargo
#

thanks. Turns out it's very easy to do

snow willow
#

Some good quality numbers there, not even any missing ones

desert cargo
#

Unfortunately you don't seem to be able to right align them

#

Even with the "align right" option

#

So you'll have to excuse the nasty row labels

snow willow
#

I can't unsee that none of them are centered properly

#

Even the column labels

desert cargo
#

They can only be left aligned

snow willow
#

What is it, imgui?

desert cargo
#

Handles.Label

#
{
    var textStyle = new GUIStyle
    {
        alignment = TextAnchor.MiddleRight,
        normal = {
            textColor = Color.yellow,
        }
    };
    for (var i = 0; i < _size.y + 1; i++)
    {
        var start = new Vector2(-extents.x, -extents.y + i * _cellSize);
        Gizmos.DrawRay(
                start,
                new Vector2(worldSize.x, 0)
        );
        if (i < _size.y)
        {
            Handles.Label(start + new Vector2(-30f, _cellSize / 2), i.ToString(), textStyle);
        }
    }
}
still tendon
#

hey. i need help again

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

public class GameOverScreen : MonoBehaviour
{
    public Text text;
 
    public void Setup(int points)
    {
        gameObject.SetActive(true);
        text.text = points.ToString() + " Points";
    }

    public void ExitButton()
    {
        SceneManager.LoadScene("MainMenu");
    }
    public void RestartButton()
    { 
        Bullet.k = 0;
        SceneManager.LoadScene("Game");

    }

}
#

this is the code for my game over screen(a image in a canvas with buttons)

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

public class EnemyScript : MonoBehaviour
{
    public GameOverScreen GameOverScreen;

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.name == ("EasyMovementPlayer(Clone)"))
        {
            Time.timeScale = 0f;
            GameOverScreen.Setup(Bullet.k);
        }
        if (other.gameObject.name == "HardMovementPlayer(Clone)")
        {
            Time.timeScale = 0f;
            GameOverScreen.Setup(Bullet.k);
        }
        if (other.gameObject.name == "Collider")
        {
            Destroy(gameObject);
        }
        
    }
}
#

here i am calling it

#

but it wont show the image

abstract olive
#

As always with these collision issues, Debug.Log inside your collision code to verify it's even happening.

still tendon
#

thougt the same thing but nope

abstract olive
#

Nope, what?

still tendon
#

its not an issue with the colliding. It gets into that code there

#

its just the setup method

abstract olive
#

Okay, then the next obvious one would be to debug the name of the object you're colliding with.

#

You need to step through your code, and Debug.Log the values so you can see what the code is doing.

snow willow
still tendon
#

yes. It gets into the setup method and sets the timeScale to 0 and then it runs through the setup method but the is active checkmark doesnt get set

snow willow
#

put a script called PlayerMovement on your player and give it a field like MovementType and check that

snow willow
#

do you have any errors in console?

still tendon
#

nope

#

it just doesnt set the image active

snow willow
#

you're referencing the wrong object

#

how did you assign GameOverScreen?

#

What did you drag into the slot in the inspector?

still tendon
#

i dragged the image from the canvas with the buttons into it

snow willow
compact knoll
#

The game over screen is not active so the script that is activating it is not active since the code is on itself

still tendon
#

yes but the code gets active at the right time or dont i just get what you mean

#

i mean it gets into the setup method

#

i made a debug.log

#

it seems like theres a problem with the gameObject.setActive(true) method

compact knoll
#

Call the set active from somewhere else

snow willow
#
            Time.timeScale = 0f;
            GameOverScreen.Setup(Bullet.k);
            Debug.Break();
            Debug.Log($"Setting {GameOverScreen} to active", GameOverScreen);
#

do this

#

then click on the log message when it runs

#

one click

#

and it will take you to the object that you are activating

#

I assure you it will be active.

still tendon
#

yes it is

#

or it says

#

But not the Game Over Screen

hallow stump
#

Simple topdown movement code. For slick surfaces

#
public LayerMask slickSurface;
public bool slick;



void Update()
    {
        if (stepTimer > 0f)
        {
            stepTimer -= Time.deltaTime;
        }

        Vector3 moveHorizontal = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        Vector3 moveVertical = new Vector3(0f, Input.GetAxis("Vertical"), 0f);
        slick = Physics2D.OverlapArea(new Vector2(transform.position.x, transform.position.y - 2.2f), new Vector2(transform.position.x, transform.position.y), slickSurface);
        if (slick == false)
        {
            rb2d.velocity = Vector3.zero;
            transform.position += moveHorizontal * Time.deltaTime * speed;
            transform.position += moveVertical * Time.deltaTime * speed;
        }
        else
        {
            if (Input.GetKey(KeyCode.RightArrow))
            {
                rb2d.AddForce(new Vector2(speed, 0), ForceMode2D.Force);
            }

            if (Input.GetKey(KeyCode.LeftArrow))
            {
                rb2d.AddForce(new Vector2(-speed, 0), ForceMode2D.Force);
            }

            if (Input.GetKey(KeyCode.UpArrow))
            {
                rb2d.AddForce(new Vector2(0, speed), ForceMode2D.Force);
            }

            if (Input.GetKey(KeyCode.DownArrow))
            {
                rb2d.AddForce(new Vector2(0, -speed), ForceMode2D.Force);
            }

        }```
proven star
#

I'm not sure if this is the right place to ask but what would be the best way to go about making a pixel character customization system with sprites animated outside of unity?

#

Or something with the same effect

hallow stump
#

photoshop and if you can't get that a photoshop clone

proven star
#

I'm using aseprite

#

Thanks for the link!

proven star
hallow stump
#

well with animating outside of unit its basically picture by picture

idle mountain
#

For some reason my SerializeField isnt working.

the line of code is just: But it wont display
[SerializeField] Collider2D standingCollider;

#

πŸ˜…

#

fixed it haha

boreal cobalt
#

hey i got lil question, what is better to do for example i want to get my RigidBody2D - to put it public and drag it in the inspector or to do
myRigidBody = GetComponent<RigidBody2D >();

thanks

abstract olive
#

Whatever is better for you, it makes no difference.

boreal cobalt
#

ok thanks πŸ™‚

steady idol
#
GameManager.ShowText (System.String msg, System.Int32 fontSize, UnityEngine.Color color, UnityEngine.Vector3 position, UnityEngine.Vector3 motion, System.Single duration) ```
#

help?

#

@abstract olive

shadow shell
#

Hey, so I'm trying to clamp my player's rotation, but for some reason my object just starts spazing out?
Here's the line of code I use (it's in the FixedUpdate)

transform.rotation = Quaternion.Euler(0,0,Mathf.Clamp(transform.rotation.eulerAngles.z, -20f, 20f));
#

I debug.logged the Clamp and it's also setting the z rotation to 20, instead of -20 when the value goes beyond -20

dusky roost
#

Hey guys i am relatively new to unity and i ran into a problem. In my project i tried to make a game, where the player has to type in a random pattern o the wasd keys in a period of 3 seconds, to add force to a y-axis frozen rigidbody attached to a cube, so that it would should up as the counter reaches zero. I am not sure, if that is even possible to make, but i still tried it. The problem i ran into is, that i used a while statement in the start method of a script attached to the cube, which would check, if the counter is still greater than zero, so that the cube would stay frozen. But somehow when i try to test this code, my game would just endlessly load. I will send the could. maybe some of you could check it πŸ˜…

#

this is my script for the timer

#

this is the one where i tried to keep the cube frozen till the timer reaches 0

simple moss
#

The start method ( which is only called once) needs to finish before the update method is called.

steady idol
#
GameManager.ShowText (System.String msg, System.Int32 fontSize, UnityEngine.Color color, UnityEngine.Vector3 position, UnityEngine.Vector3 motion, System.Single duration) (at Assets/Scripts/GameManager.cs:40)
Chest.OnCollect () (at Assets/Scripts/Chest.cs:15)
Collectable.OnCollide (UnityEngine.Collider2D coll) (at Assets/Scripts/Collectable.cs:13)
Collidable.Update () (at Assets/Scripts/Collidable.cs:24)```
lean estuary
#

@steady idol You've been told what this means a number of times. Your method is not implemented. And again. You can find programming tutorials pinned in #πŸ’»β”ƒcode-beginner . Start with those.

desert cargo
#

That doesn't really happen by accident

steady idol
#

okay

ruby karma
#

I feel like their IDE generated code for them and now they have no idea they actually have to fill in the blanks

steady idol
#

So i did some research and debugged. internal void Show(string msg, int fontSize, Color color, Vector3 position, Vector3 motion, float duration) { throw new NotImplementedException(); } the cause is here. i am confused what to add here but this is linked to GameManager public void ShowText(string msg, int fontSize, Color color, Vector3 position, Vector3 motion, float duration) { floatingTextManager.Show(msg, fontSize, color, position, motion, duration); } there is no point adding this two places. What am i doing wrong?

plush coyote
#

yeah I mean... this literally says "throw an error"

#

so as long as that code is there, an error will be thrown

#

what you do with that information is up to you

lean estuary
hollow remnant
lean estuary
paper timber
#

Is there a way I can retrieve the rendered image from a SpriteShapeRenderer?

#

I'm using SpriteShape for flexible objects with repeating textures like chains and pipes and looking to work out a drop shadow

#

i should probably just use a shader

maiden forge
maiden forge
snow willow
#

compression

#

turn off compression in the import settings

agile willow
#

thanks

vapid lion
#

I'm getting this error:
CS1022: Type or namespace definition, or end-of-file expected.

what's went wrong? 😦

snow willow
#

It expected to see the end of the file but saw your } instead

vapid lion
still tendon
#

Hello. I have an Canvas which should bee on top of my sprite. this is the inspector of the canvas

#

and this is the inspector of the sprite

#

But the problem is that the sprite gets shown on top of the canvas

#

and idk if thats important but i instantiate the sprite

coral yarrow
#

Hey guys, quick tip that I need, I am making a 2d platformer game with some complex mechanics. To move the player around. Should I use the velocity, the trasnform or the addForce?

#

I've seen a lot of people use the velocity but apparently it's not a good idea since you overwrite the value that the engine processes

subtle vessel
# coral yarrow Hey guys, quick tip that I need, I am making a 2d platformer game with some comp...

There are a lot of factors and trade-offs. Some possible directions:

  • If you don't want to use Unity's built in physics and collision detection, you can just skip having a rigidbody completely and use transform. (probably not recommended)

  • If you want to completely rely on Unity's physics system and get the most out of it, use AddForce. This will give you a totally physics based game, which can be good or bad. It makes it really easy to get objects to interact with each other, but it makes it much harder to take full control of how things move. This is great if you want something that feels kind of like Angry Birds. Also good for things like Pong or brick breaker games.

  • If you want to use Unity's phsyics system for collision detection, but you want to control the movement of your object internally, you should use Rigidbody2D.MovePosition (and maybe set the Rigidbody2D to kinematic, depending on exactly what you want). This will give you complete control over where the object moves to, but if it collides with things on the way it will still trigger OnCollisionEnter2D/OnTriggerEnter2D, and it will still push other objects. If you do this, you need to keep track of the velocity of the object in your script and figure out where it should end up each fixed update using your own internal velocity. (This is probably the best option for a platformer, but it also has a lot of complexity to it)

coral yarrow
#

@subtle vessel Thank you for the detailed answer! I will investigate further into that but I think MovePosition is a good start

blissful hinge
#

Hey, does anyone know if it is possible to put an OnTriggerEnter2D in a method?

#

I want to be able to detect collisions/triggers, but only a certain times

still tendon
#

hello , i am a beginner and i amtrying to make movement for a platformer , and i am unnable to get my movement right , the character either slides , either overwrites , and i dont know how i could make it , here is my current code its problem right now is that it slides

#
 if (Input.GetAxis("Horizontal") > 0)
        {
            rb.velocity = new Vector2(speed, rb.velocity.y);
            direction = rb.velocity;
            ismoving = true;
        }
        else
         if (Input.GetAxis("Horizontal") < 0)
        {
            rb.velocity = new Vector2(-speed, rb.velocity.y);
            direction = rb.velocity;
            ismoving = true;
        }
        else
            if (ismoving)
            {
                rb.AddForce(-direction * 1);
                ismoving = false;
            }
#

i tryed to fix it by adding the else but it dosent work unless its set to really big values like 20 , and if i walk into a wall it will launch me backwards

azure prism
#

Hello maybe someone have a explication for this mistake :

I have an image(16 units in unity) and for this image the scaling is set on 100px -> 1 unity unit so the image is 1600px. and i know that my phone DPI (Galaxy S20FE) is 407 DPI so 1600/407 = 3.93 inchs = 9.98 cm or when i mesure my image on my phone the image width is 11 cm, I really don't understand where this difference comes from ...

Thanks For Your Help !

viral moss
still tendon
#

ok so i reverted my movement back to basic , ```cs

if (Input.GetAxis("Horizontal") > 0)
{
rb.velocity = new Vector2(speed, rb.velocity.y);
}
else
if (Input.GetAxis("Horizontal") < 0)
{
rb.velocity = new Vector2(-speed, rb.velocity.y);
} ```
my problem right now is that the character slides a lot after i pushed the A/D , and i tryed various ways to fix it but everything i tryed broke it
tryed doing rb.velocity = ( 0 , y ) , but it would overwrite other code , i tryed rb.velocity += ( -rb.velocity.x , y ) , that still overwrite it and it made the character bounce back when running into a wall , increasing the friction is not going to do it for me , tryed using addforce for movement but that felt even jankyer , i tryed instead of doing = do += but then my character would just shoot out of the map ; right now im out of ideas and ive been trying to make my player movement right for the past week , does anyone like to and think they could help me please ?

sharp cave
#

change rb.drag in the editor

still tendon
#

or is it a diffrent thing ? im not really good with physics and math english terms

sharp cave
#

drag against the environment i think.. think of it as wind counterforce... (long time since i used it, might be wrong)

still tendon
#

well i doubt it would work because my player used to stick to walls so in order to fix that i decreased the frictio to 0 or a really low value cant remember

sharp cave
#

give me an example, how should move work

still tendon
#

well when i hold left my character should walk left and when i let go it should stop in place ( prefered with no delay ) , it works in the physics engine

#

the main problems are the sliding , and i have some spikes wich should do knckback but they get overwriten

sharp cave
#

if you want it to to stop

#

add

#

else rb.velocity = Vector2.zero; this prevents vertical movement, use new Vector2(0f, rb.velocity.y) for limiting only horizontal movement

#

does it do what you preferred?

still tendon
#

no , not really i get stuck in the air

sharp cave
#

use the second one then

still tendon
#

oh sry im dumb i used the other one

sharp cave
#

we all were there buddy, we still are sometimes

still tendon
#

the second one wont work , that was my first try to fix it , it will overwrite other code

maiden forge
#

Will doing GetAxis make the character slide since it has to build up to 1?

Or can that not be the issue at all?

still tendon
#

idk , i think GetAxis just makes it friendly to more hardware like controlers for example

#

i also am so comfused because all unity tutorials and stuff have the movement the exact way i did it but this kind of movement just feels so broken , it overwrites lots of things and just idk , maybe using this kind of movement has sense but as a beginner im unable to understand it

#

ive been working on this movement for about a week or more and for today i have worked since 9 am until now (it is 3 pm) with no progress , ive been watching tutorials reading from the api , asking on discord , serching on google , reading reddit post and more

maiden forge
#

Do the players slide in the tutorials at all?

#

Or do they straight up stop when they release keys?

still tendon
#

they do player slide or just do the simple fix wich overwrites evrything all the time

#

no tutorial i have seen covers the stopping of the player other then increasing friction wich affects movement and wall sticking or just set velocity to 0

#

look here is the code that covers left right movement and the spike , maybe the problem is the spike idk

if (Input.GetAxis("Horizontal") > 0)
        {
            rb.velocity = new Vector2(speed, rb.velocity.y);
            direction = speed;
        }
        else
         if (Input.GetAxis("Horizontal") < 0)
        {
            rb.velocity = new Vector2(-speed, rb.velocity.y);
            direction = -speed;
        }

  void OnCollisionEnter2D(Collision2D coll){

if (coll.gameObject.tag == "spiketagtest"){

health-- ; // decrements by one
lives.text = health.ToString();  // converts int to ui text

rb.velocity = new Vector2( -direction, jumpheight);   // this kinda works  , overwriting breaks it
        }
   }
viral quartz
#

Maybe you could have a public bool tweenComplete as a buffer between the two?

so in the Coroutine you can write while(!otherComponent.tweenComplete) yield return null;

and in the tweeningCode :

.OnComplete( () => tweenComplete = true;)```
#

@stray carbon

#

Np! Just realized you can also use yield return new WaitUntil(otherComponent.tweenComplete); for aesthetic reasons. I think it's the same as the while loop internally though.

honest python
#

why does my platform effector hardly work?

#

wheenever I'm moving horizontally it resets all horizontal speed for a bit

#

wait nvm that's on me :p

vale dock
#

So i have a bit of a weird setup going for the character sprite components. I have a player prefab with body parts and a character customization menu that changes the sprite of the sprite renderer of those components. I then am trying to save the current sprites of those components in my gameManager script. I do have a player script as well that my gameManager can access, so my thinking was to make public SpriteRenderer objects in my player script, drag the actual body part components from hierarchy into those slots in the editor and was hoping there was a way then for the gameManager to access those pieces sprites and save them in the gameManagers serialized fields for each sprite option i have setup (hair, body, clothes, etc.). Am i making this too complicated? or is this something that would work with my setup?

#

Tried it out, and gives error "cannot convert SpriteRenderer to Texture2D

cinder dock
#

Anyone looking for a partner to create a unity game?

snow willow
vale dock
#

ok so ive changed it a bit again, made the objects in my gameManager sprite objects and using lines like this to save "hairTexture = player.hair.sprite;" where hairTexture is the game managers sprite object, player is the player object created from player script which has a hair object that takes the hair sprite. Does this work?

vale dock
snow willow
snow willow
vale dock
#

so if my game manager has sprite objects saved, it doesnt render them, it just holds the data of the sprites i can then move back to my player script on load?

snow willow
vale dock
#

ok thank you, i think i can get something working then

pallid kayak
#

my code when the player crashes into an asteroid:

#

expected behaviour:

#

behaviour when crashing into asteroid at high speed:

#

works as expected at low speed btw

#

so why does this coroutine not finish at high speed?

heavy token
#

Do you disable or destroy the player when the collision occurs?

pallid kayak
#

i do not

#

the player animation changes to the "dead" animation

#

(which just changes the player sprite)

heavy token
#

can you show where you call the Coroutine?

pallid kayak
#

okay

#

there is also another death condition (when fuel is empty) but the bug also occurs if my fuel is not empty, so it's not a problem of those overlapping

heavy token
#

that script is on your Asteroid right?

pallid kayak
#

it is

heavy token
#

do you disable or destroy the asteroid?

pallid kayak
#

the asteroid also does not get destroyed

heavy token
#

well that is certainly something. The Coroutine looks fine and the only way how it shouldn't finish is if you call StopCoroutine somewhere

pallid kayak
#

if you want, i can send the link to my (WebGL) game where you can easily recreate the bug

heavy token
#

sure

pallid kayak
#

i have never used StopCoroutine

heavy token
#

You have no errors in your console?

pallid kayak
#

i do not

pallid kayak
heavy token
#

When you click in the console on the Debug.Log() it takes you to your Coroutine? Not that you another Debug.Log() with the same message

pallid kayak
#

it does

heavy token
#

No idea tbh. You could try and move the stuff to your PlayerMovement script and see if it fixes it. The asteroid calls a method on your Player script and that function calls the Coroutine which is also on your Player

#

wait I think I found it

pallid kayak
#

thank you

heavy token
#

Asteroids despawn after they are far enough away from the player right? So when you crash into one with high speed to you carry enough speed to get far enough away from the asteroid for it to despawn

pallid kayak
#

right!

#

but now that it's on the player, it's fine

#

because the player doesn't despawn

#

thank you!

heavy token
#

ye

#

quite a puzzle tbh

pallid kayak
#

i always get problems that are hard to solve like this πŸ˜…

#

hard to find the problem

#

not hard to solve

signal parrot
#

i can't instantiate gameObjects when i have a gameObject following the mouse cursor

#

can anyone help me

torpid junco
#

heya guys, can anyone help me with my OnCollisionEnter2D function? it just wont call. i made a unity forums thread and was told the following:

if your both collider objects have a 2d collider
if at least one of them has a rigidbody2d component
if none of them have the trigger field checked
I have done all these things but it still wont work.

sweet swan
raven jay
#

why isnt my screen warp working

#
    public float screenWidth;
        public void ScreenWrap()
    {
        Vector2 playerPos = transform.position;
        if (transform.position.x > screenWidth)
        {
            playerPos.x = -screenWidth;
        }
        if (transform.position.x < -screenWidth)
        {
            playerPos.x = screenWidth;
        }
        if (transform.position.y > screenHeight)
        {
            playerPos.y = -screenHeight;
        }
        if (transform.position.y < -screenHeight)
        {
            playerPos.y = screenHeight;
        }
        transform.position = playerPos; 

    }```
#

here the code

subtle vessel
raven jay
#

i dont need help anymore fixed it alredy

#

srry for late response

#

thx anywyas

#

anyways

valid grotto
#
Vector3 dir = player.position - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);```
I have this code on a gun so it always is pointed towards the player. It looks fine when the player is on the right side of the gun, but when the player goes on the left side, the gun gets flipped upside down. How can I fix this?
subtle vessel
#

I think SpriteRenderer has a flipX flag that you could use instead if you don't want to mess with the scale. (sorry, been a while since I did something like this)

valid grotto
fleet knot
maiden forge
#

you could change the field of view by a integer called zoom. You could change the Z Axis of the camera. There's probably more ways just depends on what way you think is best.

woeful sentinel
maiden forge
fleet knot
maiden forge
maiden forge
#

This might work or at least in the editor it states:

"should this rigidbody be taken out of physics control?"
And assuming if we set it to true then it removes the physics control..

Rigidbody2d_variable_here.isKinematic = true; // This is for 2d purposes if you're using 3d the other way should work im hoping well 3d might work in 2d depending on how you have it set up.. I have been told vector3's will work in a 2d enviorment just set the z axis to 0.

@fleet knot

still tendon
#

hello , for the past week i have been trying to make my player movement and i have tryed 4 aproaches out of wich none worked for me , i tryed to make my movement using rb.velocity= , but it overwrites other code , i tryed doing rb.velocity += and it shoots me up like a rocket , i tryed using addforce and it is just janky and inconsistent , also all of theese that i mentioned above have a slideing problem , i tryed using transform. translate and transform = ransform.right and theese also didnt work , half of my character kept clipping trough walls and all, does anyone have eny other idea of how i could aproach this ?

lean estuary
#

With forces drag is used to stabilize movement and additional edge case manipulation. Also higher gravity for snappier controller. Another alternative is MovePosition. Which is also a rigidbody method to be used in FixedUpdate.

#

Also never directly manipulate velocity unless you are writing your own physics interactions simuilation.

still tendon
still tendon
lean estuary
#

Using AddForce/AddRelativeForce

#

To implement knockback apply single force call with Impulse force mode.

#

Single impulse can be called from anywhere.

still tendon
lean estuary
#

I mean you can use single impulse outside of FixedUpdate in any event applying it. Manual describes how to use it in AddForce.

still tendon
#

so you are saying that i should use addforce for my player movement right ?

still tendon
#

why is this not working ? its the example from unity

vocal condor
#

Is speed a float?

hollow crown
#

or is this actually a Rigidbody2D

vocal condor
#

Show us the console error

#

It'll immediately inform us of the arguments you're providing it.

#

That it isn't accepting.

still tendon
#

speed is a float type of value 5

vocal condor
#

Is rb a rigid body?

still tendon
#

yes

vocal condor
#

2d?

still tendon
#

yes

vocal condor
#

I posted the wrong docs, just realized this is the 2d code channel

#

Try Vector2.right * speed

#

Without the other two zeros

still tendon
#

speed has the value 1 right now btw

#

idk why but nothing works for me , ive spent a week on the movement trying every way of doing it and the same problems occur , overwriting , sliding , insane speed , to low speeds , clipping and other

vocal condor
#

Maybe the walls aren't solid or you're adding infinite force.

still tendon
vocal condor
#

Where force is so large that it's interpolated the next position well beyond the walls position and failed to determine that it should have been stopped.

still tendon
vocal condor
#

Place a log inside the if statement and see how often it is occurring or print velocity to see the speed.

#

Is this in Update or Fixed Update?

still tendon
#
if (Input.GetAxis("Horizontal") > 0)
        {
            rb.AddForce(Vector2.right * speed, ForceMode2D.Impulse );
        }

this is all the code for the right movement

vocal condor
#

Input should be handled in Update. Physics usually in Fixed Update.

still tendon
vocal condor
# still tendon ```cs if (Input.GetAxis("Horizontal") > 0) { rb.AddForce(Vec...

That shouldn't be a concern at this level; of course that's correct, although I would have approached it by simply doing something like this:cs rb.AddForce(Vector2.right * speed * inputX, ForceMode2D.Impulse); Where inputX is assigned the value Input.GetAxis("Horizontal"). Mobile coding, error prone - no Intellisense.

#

Where inputX would have been acquired in Update.

#

Input isn't updated in Fixed Update so you've got a possibility of adding a great amount of force for false positives relative to input detection.

still tendon
#

yeah i know i have done the inputs in update and physics in fixed update before but after loosing over 60 hours on some simple movement i deleted the script severeal times and did not bother to write that every time

vocal condor
#

Print the velocity

#

And see if it's within your expectation; this is called debugging.

still tendon
vocal condor
#

print(rb.velocity)

still tendon
#

and i am suposed to put this in update ?

vocal condor
#

Place it in your if statement

#

So you aren't spammed

#

Any where would be fine but you'd get more spam depending on where you've placed it.

still tendon
vocal condor
#

Right, so it's going extremely fast

#

300+

#

You can improve collision detection a bit by using continuous detection mode

still tendon
#

i am still shooting at insane speeds , the walls are not my main problem right now πŸ˜†

still tendon
#

this is a question for multiple people , do you think i should avoid unitys physics engine for a 2d platformer game ? i have read a lot of post wich said that it is bad for this and others that said it is good , i personaly am unable o do simple movement without overwriting stuff , for me it also feels really inconsistent , now , count the fact that i am a beginner and i might have theese problems because of the lack of experience so i am asking you if i should ditch the physics engine or keep using it for 2d games (a platformer in this case)

dusky roost
raven jay
#
public int currentHP;
    public GameObject Meteor; // These are to find the GameObjects
    public GameObject Player;
    
    void Start()
    {
        (Meteor) = GameObject.Find("Meteor"); // Set this to the GameObjects name
        (Player) = GameObject.Find("Player"); // Set this to the GameObjects name
    }
    void Update()
    {
            if (currentHP < 1) // This is to destroy the player when you reach 0 HP
        { 
            Destroy(Player); // You can change this to a different method
        }      
    }
    private void OnCollisionEnter2D(Collision2D collision) // Detecting the damage
    {
        if (Meteor)
            currentHP =-1;
    } 
}``` i can't find collision2d in add component
still tendon
raven jay
#

ok ill try

#

well none of those exist apparently

#

i think ill use a circle collide

#

circle collider

vocal condor
#

On collision entered is a callback function that is handled by Unity. What're you wanting to do with it? @raven jay

#

In particular the first argument collision 2d.

raven jay
#

i want the meteor to do damage when it hits my player

vocal condor
#

So Collision 2d is the collision data.

#

It holds the collider that hit your character or whoever owns this script.

#

You can verify what hit you by printing the name of the Game Object that hit you.

#

What's normally done is to validate if the collider has the appropriate tag then process your necessary events.

#

Then you'd be able to do the same as what's illustrated in the Compare Tag docs.

raven jay
#

hey @vocal condor can u hop on a call with me and explain that ;-; pl

#

pls

vocal condor
#

If you're having difficulties with the collision not occurring, I've answered you in #πŸ’»β”ƒcode-beginner; this is greatly cross posting now.

turbid heart
#

break down the steps
1)how to make something walk
2)how to set the direction
3) how to random the direction
4) how to random with constraints(i'm assuming you dont want it to walk through the ground, or into the air)

flint geode
#

i got a random movement script so my crab randomly moves left, right, forwards, backwards.. Forwards and backwards don't work.. It only moves left and right.. no errors. Any help?

#

NVm i fixed

still tendon
#

is unitys character controller (3d) suitable for 2 d games ?

snow willow
distant pecan
dense charm
#

Best way to solve fast moving bullets going through walls?

snow willow
dense charm
#

use continuous collision detection
I've tried this but it doesn't seem to work Sadge

snow willow
#

try the other 5 things πŸ™‚

maiden forge
dense charm
maiden forge
dense charm
maiden forge
dense charm
maiden forge
silk narwhal
#

This is what I've been working on

#

Green buttons for score and red buttons for death

#

When I press one of the green buttons, the set changes randomly

#

But sometimes this happen

#

And that's a problem I'm unable to solve

#
using System.Collections.Generic;
using UnityEngine;

public class ButtonSpawner : MonoBehaviour
{
    public GameObject[] Buttons;

    //private List<GameObject> Instantiated;

    void Start()
    {
        StartSpawning();
    }

    public void DestroyButtons()
    {
        GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("Button");

        foreach(GameObject target in gameObjects)
        {
            Debug.Log("Destroying buttons");

            GameObject.Destroy(target);
        }
    }

    public void StartSpawning()
    {
        GameManager.GlobalObject.ButtonPressed = true;

        Debug.Log("Spawning random buttons");

        int random = Random.Range(0, Buttons.Length);

        Instantiate(Buttons[random], transform.position, Quaternion.identity, transform);

    }

 }```
#

This is the button spawner script I assigned in each of the spawners

#
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ButtonManager : MonoBehaviour
{
    List<ButtonSpawner> ButtonSpawners;

    public GameManager ButtonPressed;

    void Start()
    {
        ButtonSpawners = GameObject.FindObjectsOfType<ButtonSpawner>().ToList();
    }

    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player" && GameManager.GlobalObject.ButtonPressed == true)
        {
            ButtonSpawners.First().Invoke("DestroyButtons", 1f);

            foreach (ButtonSpawner Button in ButtonSpawners)
            {
                Button.Invoke("StartSpawning", 1f);
            }

        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            ButtonSpawners.First().Invoke("DestroyButtons", 1f);

            foreach (ButtonSpawner Button in ButtonSpawners)
            {
                Button.Invoke("StartSpawning", 1f);
            }
        }
    }

}```
#

This is the button manager script which I assigned in the green button

snow willow
#

that's super confusing πŸ˜΅β€πŸ’«

silk narwhal
#

Now how do I remove the all red button problem

silk narwhal
snow willow
#

I'd probably manage it this way: instead of having it be purely random and independent per button, i'd pick a random number in a range

#
int numberOfRedButtons = Random.Range(minRedButtons, maxRedButtons + 1);```
#

then shuffle the slots and assign them red or green as per the number of reds chosen

#

then you're guaranteed to have a sane number of red buttons

silk narwhal
#

Where should I do it?

snow willow
#

in some kind of central manager

silk narwhal
#

ButtonManager?

snow willow
#

maybe?

#

IDK your setup is confusing

#

but does the concept make sense?

silk narwhal
#

I'm confused

maiden forge
#

Just make a way to check if theres at least 1 green button spawning..

silk narwhal
#

How do I do that?

maiden forge
#

Idk cause it doesn't look like you have a way to see if its a green or red now.. you just got buttons spawning in

silk narwhal
#

Yea

#

That's why I'm stuck

#

I have 10 spawners, 5 on each side

#

With same button spawner script assigned

#

And an array with two buttons assigned (red and green)

silk narwhal
maiden forge
#

Probably the best way to start is to do like praetorblue said and put it in the code of StartSpawning() method.

silk narwhal
#

Hmmm

#

Then I need to start from the beginning of the code

maiden forge
silk narwhal
#

Hmmm

snow willow
#

again pick a random, sane, number of red buttons (let's call this number R). shuffle the buttons list, then make the first R buttons in the shuffled list red, and the rest green.

silk narwhal
#

I am really not that good with coding (I'm sorry)

#

Let me see what I can do

maiden forge
#

Well you doing a good job for what you got at least. Edit: Got to start from somewhere

snow willow
#

Why do people apologize for not being good at programming πŸ€”

maiden forge
silk narwhal
#

Because in every server I asked this question, I got a passive aggresive response, or no response at all

maiden forge
silk narwhal
#

Damn

#

Also english isn't my first language

cinder dock
#

can anyone help me do a highscore please? I checked out tons of tuts. but it didn't work

#

Yo when I build my file with WEBGL some of my scripts don't work(They work in editor) Unity help please

silk narwhal
#

Ok I fixed my spawner, thanks

silk narwhal
#

THis is how I did it

#

And then on the player script, put the addscore function on collision

#

I recommend Brackeys tutorial about this one, he does an excellent job

cinder dock
#

My game broke when I build it

#

can someone help please

#

when I build some of my scripts don't work

#

My gameover panel

#

for e.g.

visual hare
#

i know its a boasic question bnut how to make a box move when i poress wsad

cursive geyser
#

I finally found the solution to how I wanted to implement gun spread. I was sitting in bed and came up with this:

for (int i = 0; i < bulletCount; i++) 
        {
            Instantiate(bulletPrefab, firePoint.position, firePoint.rotation * Quaternion.Euler(0,0, -maxSpread/2 + (((i + 1)/((float)bulletCount + 1)) * maxSpread)));
        }
#

its pretty neat since it allows me to make upgrades that can increase spread and also shoot bullets that arent random

#

this is pretty much the idea

alpine canopy
#

Hello

#

in Win() I want to make the player which is "this" and the camera to be in the axis that i wrote them in Vector3.....
but it doesn't seem to go there

#

:)

turbid heart
alpine canopy
#

yep

turbid heart
#

are you sure you dont want localPosition instead?

alpine canopy
#

actually no

alpine canopy
turbid heart
#

where do they end up instead? are you sure Win() is called?

alpine canopy
#

yes

#

on collision enter

turbid heart
#

no idea. not enough info

zinc kelp
#

Guys i made an jump animation like in geometry dash but when i jump the animations start but imediatly goes to idle again why's that

#
 
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
        {
            rb.velocity = Vector2.up * jumpForce;
            IsJumpingRight = true;
            
        }
        else
        {
            IsJumpingRight = false;
        }

        if (IsJumpingRight == true)
        {
            anim.SetBool("IsJumping", true);
            
        }
        else
        {
            anim.SetBool("IsJumping", false);
        } ```
maiden forge
zinc kelp
#

this?

maiden forge
#

Yes I believe that is it. It looks fine, i guess you will have to code a wait time or click setttings and try messing with it.

maiden forge
#

Could shorten it like this, but i don't see what wrongs with your character.. is it suppose to rotate when jumping or something?

if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{ 
isGrounded = false;
rb.velocity = Vector2.up * jumpForce;
IsJumpingRight = true;
anim.SetBool("IsJumping", true);
}
else 
{
isGrounded = true;
anim.SetBool("IsJumping", false);
IsJumpingRight = false;
}
zinc kelp
#

guys how i can make my player don't stop instanly and maintain a bit o velocity after i unpres a or d

#

2d

zinc kelp
#

yea but not completly

#

i want to maintain a bit of it

#

to be smoother

meager mural
drowsy canyon
#

Heya, I am using the latest unity version with the URP for 2D. I calculated a mesh as a field of vision. How to hide (darken) everything which is not inside it? I know that for 3D you could use render features as an example. But I am completely clueless how to approach this in 2D.

turbid heart
drowsy canyon
#

Okay will move it over there, ty!

still tendon
#

i need help, im doing movement using rigidbody.MovePosition() and when i collide with two colliders at the same time (for example a corner), the player slides over one of the colliders

compact knoll
#

i need help figuring out why the 45 degree angle animation is freaking out. The animation plays correctly when editing it, but when playing in game it just starts freaking out. I've even swapped 45 degrees to one of the other animations and it does the same thing. There is no difference in the code for it versus the other animations. all the animations do is rotate 180 degrees from a given start to a given end.

snow willow
compact knoll
#

yeah, just setting which animation to play based on the angle which can only ever be one of 8 angles

#

it also only does the check in start since i instantiate the sword at the correct angle

snow willow
#

If it's cloudy out and the computer's feeling frisky, it might return -45, but if It's a Wednesday in February it might return 315 instead

#

and both of those are equally valid and likely

compact knoll
#

right but it's reading it correctly. i'm printing it in the console and using a switch statement to choose the animation. it plays the correct animation, it's just the animation decides to freak out at just that angle

#

it also only uses the angle value once to choose the animation to play, it doesn't actually make any difference once the animation has started playing

#

This is how it chooses the animation to play: https://hatebin.com/kamqwhmrgd
This is only done in start. It's probably not the most efficient way of doing it, but everything but the one angle works correctly. I've even changed the animation that plays at the 45 degree rotation to one of the working animations and it does the same thing

snow willow
#

does that work?

#

(think it should replace all that code)

compact knoll
#

huh that does. but why does that work but the switch doesn't? it should be using the same values, right?

snow willow
#

or if your angle is not 45 but slightly off... maybe 44.999999 or 45.000001

compact knoll
#

i was logging the value to the console one line before it checked it for the switch and it always returned 45

snow willow
#

did you log it at full precision?

#
Debug.Log(transform.eulerAngles.z.ToString("F8"));```
#

either way - I avoid transform.eulerAngles like the plague - at least reading from it

#

setting it is usually fine

compact knoll
#

i guess for some reason it wasn't the correct value for just that angle πŸ€·β€β™‚οΈ i just threw a default into my switch and it played the default one when at the 45 degree position. So i'll just use the simplified one you gave me and will actually do math next time instead of being lazy and throwing the options in a switch lmao

maiden forge
#

For anyone having problems with running into solid objects that aren't there like i had i created a composite collider 2d and set the radius to 0.01

charred cairn
#

I'm new to making unity games and I was wondering how to make a collision with tiles. (Context: I'm trying to make a spike that if you run into in, it resets the scene. I already have the reset scene bit i don't know how to do the collision.)

maiden forge
charred cairn
#

thank you so much

slim forge
#

How can i smooth my player movement like Input.GetAxis does?

charred cairn
maiden forge
charred cairn
snow willow
charred cairn
#

yes

maiden forge
random hinge
#

Nice

maiden forge
# charred cairn

Also make sure this is capitilized and etc for the code because i just typed what i could remember.. C is case sensitive on coding.

And make sure your tag and the string you have typed for tag is exactly same.

maiden forge
random hinge
#

I preferably use bolt because I’m to stupid for c# -_-

maiden forge
charred cairn
#

the tags are exactly how they are spelt

maiden forge
#

that's because comparetag in C# is caps bro.. your error is being thrown because its not properly capilitized.. I told you it was case sensitive.

#

CompareTag - you have comparetag

charred cairn
maiden forge
#

this is how i would code it, which is similar to yours haha.

    private void OnTriggerEnter2D(Collider2D other) {
        if (other.gameObject.CompareTag("Spike")) {
              SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }```
charred cairn
#

im coding it in void update, is that the problem?

maiden forge
#

Methods aren't suppose to be inside of methods.

charred cairn
#

don't worry about what's in the void start

maiden forge
maiden forge
charred cairn
#

ok, did that and now its telling me that it cannot convert from 'method group to 'string' I probably should just learn C# instead of wasting your timeπŸ˜†

maiden forge
charred cairn
maiden forge
#

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); - change it back to this

charred cairn
maiden forge
#

You're welcome bud, i help when i can.

maiden forge
# charred cairn EPIC IT WORKS thank you so much for spending your time helping me, who doesn't k...

If you want to copy any of the code from here: https://pastebin.com/u/UnityCoder_Jay/1/kad0N8sz
Or even look at it for help/reference you can. Its my pastebin, it has comments of what stuff does to try to help you and not just code..

Let me know if you find any errors in it.. I currently use it some of it. So it shouldn't have errors if you set it up correctly.

runic orbit
#

I have question. what is better, One canvas with instantiated prefabs of enemies or enemy instanitated outside canvas but each have own canvas?

faint hollow
#

Hello! I'm new doing some game programming with Unity. I'm helping myself with a tutorial, but I have some technical issues and idk how to solve it

#

It says that "the name 'input' does not exist in that context". So basically my game doesn't work. Idk what to do :c

still tendon
#

so it became pretty clear the physycs atre just not the way for 2d games , at least for mine , and people say that the character cotroller(wich is 3d) is not the way , is there any character controller 2d ?

hollow crown
# faint hollow

You should configure VS so it properly functions. You should be getting autocomplete and underlined errors. Config instructions are in #854851968446365696

faint hollow
#

Thank you guys!

faint hollow
#

Thank you thank you!

zinc kelp
#

Guys how i can make my player keep some momentum after un-press a or d to be more smoooth

#

becouse is stoping instantly and looks choppy

modest cargo
zinc kelp
#

@modest cargo thanks i made it work

#

i changed the getaxisraw to getaxis

clever crown
#

I'm trying to add hover text to a game object. Is using unity ui and a script to change text a smart way of going about that

rigid kindle
clever crown
#

ok thanks

rigid kindle
clever crown
#

Ok thanks πŸ™‚

lament oxide
#

I'm making a simple 2D asteroids game but having an issue... I have a poly collider on my player and I rotate the player by adding torque to a rigid body, when the collider is enabled the player turns horribly slow, however when it's disabled the player turns as expected. As I don't want the player to die 1000 times over and keep it fairly optimised, I disable it for 10 seconds when the player dies to allow them to escape any asteroids on the spawn and then enable it again so they can die. Is there an easy way to make the player rotate the same regardless of the collider? Might be worth mentioning the timer, respawn and spawning etc is all in a separate script attached to the main camera. Also I cannot use a trigger as the asteroids need a collider.

        float maxSpeed = 60.0f; //max speed of player
        
        public Rigidbody2D _rb;
        private float thrust;
        private float turnThrust;
        private float turnInput;
        
        [SerializeField] private bool EnableKeyboard;
        public GameManager gm;

        void Start()
        {
            _rb = GetComponent<Rigidbody2D>();
            gm = GameObject.FindObjectOfType<GameManager>();
        }
        
        void Update()
        {
            if (EnableKeyboard == true)
            {
                turnInput = Input.GetAxis("Horizontal"); //arrow keys turning player
                //print(turnInput);
            }
            
        }
        
        void FixedUpdate()
        {
            //rotation
            float rtn = _rb.angularVelocity; //this gets rotation speed of player

            if (rtn < 150.0f || rtn > -150.0f) //if rotation is less than 150 and greater than -150
            {
                _rb.AddTorque(-turnInput * 10); //add torque
            }
        }
lament oxide
#

Okay I just went against the whole optimised thing and constantly check for a bool on the game manager now. If the players collider is active I just used an increased scalar for turning. Dumb I know, but I am not sure how else to do it...

snow willow
#

e.g. the shape of the collider

#

e.g. it's much harder to spin a large diameter wheel than to spin a skinny diameter wheel

#

Which is why ice skaters spin very fast when they pull their arms and legs in and spin slow when they extend them

#

it basically represents how hard it is to rotate the object on each axis (i.e. how much torque is required to generate a given amount of motion)

lament oxide
#

Ah, it'd be a better idea to use that, thanks πŸ˜›

snow willow
#

although I just linked you the one for 3d rigidbodies

lament oxide
#

Potatoe potato, I assume they are fairly similar

snow willow
lament oxide
#

Thanks, this is helpful ❀️

dense charm
#

Hi there, I wish to render my entire GameObject and its children to a render texture then place the result at the position of the gameobject.
Two issues, one is that it's creating a magic mirror effect, like I can see the frame inside itself over and over.
Other issue is that it crashes after like 10s of running.
What am I doing wong?
Here is my code:

{
    var renderers = GetComponentsInChildren<SpriteRenderer>();
    foreach (var renderer in renderers)
    {
        renderer.enabled = true;
    }
    _renderTextureRenderer.enabled = false;
    var pos = transform.position;
    transform.position = new Vector3(1000,1000,0);
    var camPos = Camera.main.transform.position;
    Camera.main.transform.position = new Vector3(1000,1000,-10);
    var renderTexture = new RenderTexture(Screen.width, Screen.height, 32);
    Camera.main.targetTexture = renderTexture;
    Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGBA32, false);
    Camera.main.Render();
    RenderTexture.active = renderTexture;
    screenshot.ReadPixels(new Rect(0,0, Screen.width, Screen.height), 0, 0);
    screenshot.Apply();
    Camera.main.targetTexture = null;
    RenderTexture.active = null;
    Destroy(renderTexture);
    _renderTextureRenderer.sprite = screenshot.CreateSprite();
    transform.position = pos;
    Camera.main.transform.position = camPos;
    foreach (var renderer in renderers)
    {
        renderer.enabled = false;
    }
    _renderTextureRenderer.enabled = true;
}```
ancient path
dense charm
ancient path
dense charm
#

which ik isn't optimal but I'll tidy that up after I get it working

wary briar
#

sorry is this is a dumb question but where do i go to create my own sprites ?

ancient path
wary briar
#

well i want to design my own rather then importing them from a free package in the asset store

#

but i dont know where I need to go to work on them

wary briar
#

ok i will

snow willow
#

aseprite

harsh widget
#

how to stop my player from sliding????

#

it is very annoying!

snow willow
#

set their velocity to 0?

#

apply a force opposite the direction of motion to slow them down?

wary briar
#

ok perfect i have seen a few of his videos but i guess i missed that one he is always easy to understand

ancient path
topaz root
modest cargo
#

@dim scroll @lean estuary
Here's some tests I did

lean estuary
#

How did you smooth it?

modest cargo
#

It's keyframed

#

So it's probably as smooth as it can get

dim scroll
#

I've gotten it to look fine at high res

#

hmm

modest cargo
#

The only ideal solution would be to synchronize the follow camera speed with the player's speed, to always move at regular 1, 2 or 3 pixel increments over time?

#

Assuming it's caused by the subpixel variance in distances of the camera and player

dim scroll
#

is this an animation

#

or a script

modest cargo
#

The sprite moves by animation, in third video camera is smoothed to follow the player

#

Though with such speed it's not apparent besides the jitter

dim scroll
#

what updates

modest cargo
#

LateUpdate

lean estuary
dim scroll
#

sounds like a hack

#

something that will break 2 months down the line

lean estuary
#

The vector is smoothed by some spring-damper like function, which will never overshoot. The most common use is for smoothing a follow camera.```
dim scroll
#

the annoying part is that the environment works with pixel perfect camera and the player looks smooth without it

#

if only I could combine those two things

modest cargo
#

That sounds like it'll work great under normal circumstances, but I'm not sure what that would do to the "subpixel race" issue

lean estuary
#

When you use something like Lerp(object, target, 0.01f) instead, it never reaches the target and creates jitter

modest cargo
#
    void LateUpdate()
    {
        float dist = Vector3.Distance(transform.position, target.position);
        transform.position = Vector3.SmoothDamp(transform.position,target.position, ref velocity, SmoothTime);   
    }

This is the follow camera

#

Lerp is worse in that regard, definitely

lean estuary
#

so if you get jitter even with this (don't forget interpolation on rigidbody) syncing frames with fixe will fix it for the editor

#

It should work quite fine in the build though even like this

dim scroll
#

yeah

modest cargo
#

What do you mean by syncing frames?

dim scroll
#

the only issue is pixel perfect camera

#

otherwise its totally fine

#

but I need it to make everything else to look good

lean estuary
modest cargo
#

That seems
terrifying?

lean estuary
#

by default fixed frames are set to 50

#

when they are in step there's no jitter during updates

modest cargo
#

Looks like that makes physics framerate dependent, and limits FPS using a very unreliable method

lean estuary
#

Well again, that's mostly to fix things in the editor. Previous code would make sure that it will work fine in the build

dim scroll
#

so I need a solution that fixes the static objects

#

or a solution that makes pixel perfect not break my character movement

#

in theory this should be simple πŸ˜”

modest cargo
#

I might look into this more because it bothers me

#

But this seems like quite a fundamentally challenging problem

dim scroll
#

It doesn't seem like it due to this

#

I just have a very weak grasp on how pixel perfect camera works

#

I can't for the life of my make my environment sprites not jitter

lean estuary
#

I think it's not the movement that is the problem with those objects

#

They look like they are not using correct pixel per unit and being extrapolated

dim scroll
#

I just have no idea what the issue is

modest cargo
#

There's something weirder going on with those

#

They move almost a whole two pixels relative to camera before anything else does

lean estuary
#

algorithm moves pixels around to fit them to pixel perfect specific size

modest cargo
#

Still, extremely not in sync

dim scroll
lean estuary
#

make sure your assets have the same ppu settings and are not rescaled

agile violet
#

hello i have an error

#

give me a second to send it

#

the dark tiles are supposed to be "walls"

#

but i can't give them colliders

#

because they're part of a tileset

#

how would i make the player unable to walk through the wall

modest cargo
#

Tilemap Collider?

agile violet
#

im brand new

agile violet
#

you're gonna have to explain

lean estuary
dim scroll
agile violet
#

ok

#

thank you

lean estuary
modest cargo
#

Youtube has many tutorials about unity's tilemap colliders

modest cargo
lean estuary
#

I've tried using pixel perfect package, it has a lot of options handling rescaling of pixel assets for you, I prefer calculating pixel perfect ratio and correct zoom step levels myself to keep it.

dim scroll
#

assets with odd numbered dimensions move before assets with even numbered ones

modest cargo
#

Ah, interesting
Dimension as in object or asset?

dim scroll
#

all odd numbered assets need to be clamped half a pixel extra

#

I mean sprites

#

ill just make sure im only using even numbers

modest cargo
#

Familiar with the rule to always use power of two dimensions?

lean estuary
#

This is also important because it is needed for the compression ^^

dim scroll
#

well

#

my artist kinda just gives me massive sprite sheets, the props are all arranged randomly

#

so I used automatic

#

Ill have to make sure its always even numbers

modest cargo
#

Can't recreate the jitter with NPOT textures either

#

But if you got it fixed, that's what matters isn't it

dim scroll
#

the problem now is my sprite editor is super laggy

dusky fable
agile violet
#

is there any way to remove this big ass icon in the middle of myscreen

snow willow
agile violet
#

ty

#

one more issue

#

i uh

#

well

#

how do i set the camera back to the center

#

in the scene

#

i zoomed out a little far

late viper
agile violet
#

ok ty

vocal tiger
#

hey guys in my game the speed of my object changes when the size of the screen changes

#

when its in full hd the object moves slowly and when its in free aspect it moves normally

#
        if (!hasStarted) {
            
        }
        else {
            transform.position -= new Vector3(0f, -beatTempo * Time.deltaTime, 0f);
        }
    }``` this is what I am using to move the object
#

the object is also on the canvas

vocal tiger
#

its a float that is 400

#
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class Move : MonoBehaviour {

    public float beatTempo;

    public bool hasStarted;
    // Start is called before the first frame update
    void Start() {
        hasStarted = true;
    }

    private void Update() {
        if (!hasStarted) {
            
        }
        else {
            transform.position -= new Vector3(0f, -beatTempo * Time.deltaTime, 0f);
        }
    }
}``` here is my full code
late viper
vocal tiger
late viper
#

you need to change the movement based on the screen size

vocal tiger
#

I understand

#

I can use if (canvas.width == && canvas.height==)

agile violet
#

hello i have a bug

#
    protected virtual void OnCollide(Collider2D coll)
    {
        Debug.Log(coll.name);
    }
}
#
    protected override void OnCollide(Collider2D coll)
    {
        Debug.Log("test");
    }
#

i'm trying to get the 2nd block of code to override the first one

#

but the console just logs

#

player_0

#

instead of "test"

#

nevermind, i just realized i'm an idiot

left nest
#

Hello, I want to make a simple base building game and I am struggling with one simple thing, how can I code it so than where ever I click it places a tile to the grid? I have looked at many videos but none got quite what I wanted and I couldn't find much help on the net, so can anyone help me?

coral tusk
still tendon
#

garry's mod moment

coral tusk
#

Hey guys, how can I get the direction of a collision with a CircleCollider2D?

glad goblet
#

Something like this:

        {
            Vector2 direction = collision.transform.position - transform.position;
        }```
late viper
#

<@&502884371011731486>

timid plover
#

Got em! Thanks πŸ™

coral tusk
#

Thanks

maiden forge
#

I clicked off chat for like 3 minutes and someone already breaking the rules..

late viper
#

Just a spammer, nothing to see

old zephyr
#

hey so ive been working on a simple enemy that follows the player and shoots it but i ran into an issue this is my enemy move script https://pastebin.com/UtqvUJDm and this is my enemy shooter script```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyShootPlayer : MonoBehaviour
{
private float TimeBtwShots;

private Transform player;
public float startTimeBtwShots;
public GameObject projectile;
public Transform firepoint;

void Start() 
{
    player = GameObject.FindGameObjectWithTag("Player").transform;
    TimeBtwShots = startTimeBtwShots;
}
void Update()
{
   if(TimeBtwShots <= 0) 
   {
       Instantiate(projectile, firepoint.position, Quaternion.identity);
       TimeBtwShots = startTimeBtwShots;
   }
   else
   {
       {
           TimeBtwShots-=Time.deltaTime;
       }
   }
}

}

#

ill send a video of the issue in a sec

dusky wagon
#
public class Conveyor_Belt : SwitchReactor
{
    public Rigidbody2D rb;
    public float speed;
    Vector2 pos;
    private void FixedUpdate()
    {
        if (trigger.activated)
        {
            pos = rb.position;
            rb.position += Vector2.left * speed * Time.fixedDeltaTime;

            rb.MovePosition(pos);
        }
    }
}```
I tried following a tutorial on make conveyor belts by moving the object to the left with rb.position which doesnt apply friction and then moving it in the other direction by the same amount with rb.MovePosition which does apply friction, and it works on an object in my game, but not on the player. What are possible reasons for that?
#

Okay I found it, its because the physics material of the player doesnt have friction, but Im not sure how I would fix it. I dont want the player to have friction as he can just stick to walls with it

snow willow
dusky wagon
#

How did I not think of that

#

Thank you very much

zinc kelp
#

guys my flip method doesn't work , i made and particle system that should work when the player flip the sprite buttt is not working,i made a texture to test it and the flip is not working and i think this is the problem

#
void Flip()
    {
        CreateDust();
        facingRight = !facingRight;
        transform.Rotate(0f, 180f, 0f);
    }

#
if (input < 0 && facingRight)
        {
            Flip();
        }
        else if (input > 0 && !facingRight)
        {
            Flip();
        } ```
old zephyr
#

it shoots itself

#

when its turned to the left

snow willow
#

right now you're just spawning it in as normal and presumably it goes right when it spawns

#

gotta tell thee projectile script to shoot left, or rotate it so it does

old zephyr
#

ok

#

still no succes

#
if(transform.position.x < player.position.x)
        {
            //enemy is left of the player move left
            rb2d.velocity = new Vector2(moveSpeed, 0);
            transform.localScale = new Vector2(-1, 1);
            firepoint.localScale = new Vector2(-1, 1);
        }
        else if (transform.position.x > player.position.x)
        {
            //to the right side of the player move right
            rb2d.velocity = new Vector2(-moveSpeed, 0);
            transform.localScale = new Vector2(1, 1);
            firepoint.localScale = new Vector2(1, 1);
            
        }```
snow willow
snow willow
#

See this? You are spawning the projectile at a position with a rotation

#

that's all the projectile knows

#

you need to tell it somehow to go in the opposite direction

old zephyr
#

oh yeh

#

i was searching on how instantiate works but no results

#

i tried Lookat and then player.position

dusky wagon
#

I am having an error that only happens when you dont play with maximise on play. I have a conveyor belt and when you start it in the window mode it has a lot more force than when on full screen

#
 public float speed;
    public List<GameObject> onBelt;
    public Animator anim;

    private void Update()
    {
        if(trigger.activated >= 1)
            foreach (GameObject i in onBelt)
            {
                Vector2 direction = new Vector2(speed * Time.deltaTime, i.GetComponent<Rigidbody2D>().velocity.y);
                if (Input.GetAxisRaw("Horizontal") > 0 && i.CompareTag("Player"))
                {
                    direction.x += 5.781f;
                }



                i.GetComponent<Rigidbody2D>().velocity = direction;
            }

        else if (trigger.activated <= -1)
            foreach (GameObject i in onBelt)
            {
                Vector2 direction = new Vector2(speed * Time.deltaTime * -1, i.GetComponent<Rigidbody2D>().velocity.y);
                if (Input.GetAxisRaw("Horizontal") < 0 && i.CompareTag("Player"))
                {
                    direction.x -= 5.781f;
                }



                i.GetComponent<Rigidbody2D>().velocity = direction;

                foreach (Behaviour Script in disabledScripts)
                {
                    Script.enabled = false;
                }
                foreach (Behaviour Script in enabledScripts)
                {
                    Script.enabled = true;
                }
            }

        BehaviourEnable();
        anim.SetInteger("Activated", trigger.activated);
        
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        onBelt.Add(collision.gameObject);
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        onBelt.Remove(collision.gameObject);
    }
#

This is my script

#

The only reason I can imagine for it having more force is if didnt make it frame independent

old zephyr
#

whats the error?

snow willow
#

If you run something like this in Update do you imagine it would be framerate independent?
direction.x += 5.781f;

#

Or setting velocity to a number specifically tied to deltaTime?

#

Vector2 direction = new Vector2(speed * Time.deltaTime, i.GetComponent<Rigidbody2D>().velocity.y);

#

^ When a rigidbody has velocity, the physics engine moves it at that amount of distance over time. It is already framerate independent

#

If you multiply deltaTime into the velocity, you're just going to end up with a smaller velocity when the framerate is higher

#

TLDR - do your physics in FixedUpdate!

dusky wagon
dusky wagon
still tendon
#

Can someone help me? in unity I get the error that it is waiting for the end of the file or something like that, I am new to this, check in visual studio code and there are no errors

#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMoves : MonoBehaviour
{
    public float runSpeed-2;

    public float jumpSpeed = 3;
    
    Rigidbody2D rb2d;





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

    
    void FixeUpdate()
    
    if(Input.GetKey("d") || input.GetKey("right")) 
    {
        rb2d.velocity= new vector2(runSpeed, rb2d.velocity.y);
    }
   else if if(Input.GetKey("a") || input.GetKey("left")
   {
       rb2d.velocity= new vector2(-runSpeed, rb2d.velocity.y);

   }
   else
   {
      rb2d.velocity= new vector2(0, rb2d.velocity.y) 
   }
   
    
    
 
}```
#

I was programming the movement of the character

still tendon
#

let me check again

#

same

#

...

snow willow
#

else if if(Input.GetKey("a") || input.GetKey("left") < this for example is a disaster

still tendon
#

oh, thanks

still tendon
#

in first scene the script works fine, but in second it captures EventSystem GameObject all over the screen

#

both scenes are almost identical and i dont know why does it do this

#
if (Input.GetMouseButtonDown(0) && EventSystem.current != null && !EventSystem.current.IsPointerOverGameObject())
  {
    Debug.Log("hit ball");
  }
  else
  {
    Debug.Log("hit button" + EventSystem.current.tag);
    buttonClick = true;
  }
#

can someting in canvas, order or layers affect this?

noble sorrel
#

Is there a good alternative for a canvas?
I try to use UI sprites as images in my canvas but it always just looks not quite right compared to my game sprites
I tried building the UI just with gameObjects in the scene but then if I try to attach those UI gameobjects to the camera for example they jitter very badly
any ideas?

modest cargo
#

@lean estuary @dim scroll here's another demonstration how a smoothed camera follow will jitter if the camera and the follow target are snapped to a grid, as is in pixel perfect

dim scroll
#

btw I fixed my issue

modest cargo
#

On scene view on the left it's also snapped, but moving in lockstep with the object so it's not visible

#

With the debris?

dim scroll
#

I just turned off pixel perfect and made sure that all the sprites had even numbered dimentions

#

but I appreciate all the help

noble sorrel
#

Patchi I have that exact problem in 2d

modest cargo
#

Whatever works ^^

noble sorrel
#

So its purely caused by pixel perfect?

modest cargo
#

It's caused by using a smoothly following camera with pixel perfect rendering

#

Other things can cause jitter too

#

Many other things

noble sorrel
#

Is there a way fix it while still using Pixel Perfect, I cant ditch it unfortunately

modest cargo
#

Move the camera only when necessary, or parent it to your character

noble sorrel
#

Because I use it for many different effects in my game, particles for example

#

Animations as well

#

It would be fine if canvas didnt mess up my sprites

modest cargo
#

Games like Celeste have a following camera in some scenes, and the way it's done there is that the camera moves only when the player has moved a certain distance, and even then with mostly linear motion

noble sorrel
#

Yea I got that as well

#

Heres an example of canvas stuff vs the scene

#

the bullet icon is very slightly deformed

modest cargo
#

Iirc canvas is excluded from pixel perfect?

dim scroll
#

^^

#

probably the image isn't sized properly? or the pixels dont align with the screen pixels?

still tendon
#

Can someone explain to me why I get those errors?

noble sorrel
#

Yea the canvas is Screen space overlay

modest cargo
#

If you disable scaling from UI images and use them at integer scales, they should show up correctly, right

noble sorrel
#

and not connected to the cam

still tendon
#

srry

#

ty

noble sorrel
#

Heres how it looks without scaler

#

No weird stretched pixels

modest cargo
noble sorrel
#

I assume disabling the canvas scaler component will no longer do that for diff resolutions

#

ehh nvm disabling it has the same issues egghh

maiden forge
# still tendon Can someone explain to me why I get those errors?

Any form of statements or public variables must require a end punctuation on them and some require you give them a name.

Here are some random examples:

// Variables
public float floatNumber = 5f; 
public int IntegerNumber = 5;
public string name = "John";

// Statements
Debug.Log(string);
Debug.Log(IntegerNumber + 3);
// Calling to a method or also known as a void. 
Win();

// Void - Also known as a method. 
private void Win() {
   Debug.Log("You won!");
}

// This method/void requires a variable caleld "name". 
// When methods/voids require a variable we call them Parameters. 
// So, you could say programmatically "This Win method requires 1 string parameter." 
private void Win(string name) {
   Debug.Log(name + " You win");
}
// Then you could call to it like such:
Win("John"); // This call to the Win method above is filling in the string name..
still tendon
#

"The name 'rb2D' does not exist in the current context" someone explain to me?

#

forget it, I already solved it

maiden forge
still tendon
#

I added that and I get this now

maiden forge
still tendon
#

this is the complete code

#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMoves : MonoBehaviour
{
    public float runSpeed = -2;

    public float jumpSpeed = 3;

    rb2D GetComponent = Rigidbody2D;

    private Rigidbody2D rb2d; 


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

    
    void FixeUpdate()
    {
        if(input.GetKey("d") || input.GetKey("right"))
        {
            rb2D.velocity= new vector2(runSpeed,rb2D,velocity.y);
        }
        else if (input.GetKey("a") || input.GetKey("left"))
        {
            rb2D.velocity= new vector2(-runSpeed,rb2D.velocity,y);

        }
        else
        {
            rb2D.velocity= new vector2(0,rb2D.velocity.y);
        }
    }
}```
still tendon
dusky fable
maiden forge
snow willow
#
RaycastHit2D hit = Physics2D.Raycast(transform.position, MousePos.transform.position, 1.5f, NPCLayerMask);```
#

raycast expects a position vector and a direction vector

#

so you want something like:

Vector2 dir = MousePos.transform.position - transform.position;
RaycastHit2D hit = Physics2D.Raycast(transform.position, dir, 1.5f, NPCLayerMask);```
still tendon
#

I tried the code you sent me and now I get all this ... I'm already getting stressed

#

@maiden forge

maiden forge
still tendon
#

yea

#

no, i read her

maiden forge
#

Well did you attach the script to your player Sprite, then add a component rigidbody2d and attach that to the script that was added to your player?

#

It should look something like this but it might be different

snow willow
#

you need to just pay closer attention to detail

still tendon
#

I add it, but I get that error

#

That is most likely, because I am guided by a tutorial on YouTube, but I put exactly the code that is in the video and it is full of errors

#

also that coincidentally today is my first day programming (in general)

maiden forge