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

1 messages ยท Page 25 of 1

pearl patio
#

well

#

oops

#

you should do
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal"), rb2d.velocity.y)* speed;

#

hum wait

#

rb2d.velocity = new Vector2(Input.GetAxis("Horizontal")*speed, rb2d.velocity.y);
now this should be right xD

upper wedge
#

I seem to only move right

pearl patio
#

so you won't need that


        //limits the players speed
        if (rb2d.velocity.x > maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
        }

        if (rb2d.velocity.x < -maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
        }

well I don't think so

fervent ermine
#

how do i use the sprite collider thats used for tilemapcollider2d with normal sprites

vast basin
#

Hi there. I was wondering is it possible to create a blank 2D texture and then copy portions of various other textures onto it? Am trying to create a 2D sprite that's a composite of other images.

upper wedge
#

@pearl patio It is odd, when I remove

        //limits the players speed
        if (rb2d.velocity.x > maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
        }

        if (rb2d.velocity.x < -maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
        }

It works properly but the speed is not reduced, when I keep it the speed is reduced but I can only move right even if I press the left key (the left animation plays though)

pearl patio
#

hm

#

Where do you define the value of the speed variable?

upper wedge
#

At the top of the script

pearl patio
#

wait show me your whole script

upper wedge
#
public class Player : MonoBehaviour
{

    public float maxSpeed = 3;
    public float speed = 50f;
    public float jumpPower = 150f;

    public bool grounded;

    private Rigidbody2D rb2d;
    private Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        rb2d = gameObject.GetComponent<Rigidbody2D>();
        anim = gameObject.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        anim.SetBool("Grounded", grounded);
        anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));

        //move left
        if (Input.GetAxis("Horizontal") < -0.1f)
        {
            transform.localScale = new Vector3(-0.23f, 0.23f, 0.23f);
        }
        
        //move right
        if (Input.GetAxis("Horizontal") > 0.1f)
        {
            transform.localScale = new Vector3(0.23f, 0.23f, 0.23f);
        }

        //jump with spacebar
        if (Input.GetButtonDown("Jump") && grounded)
        {
            rb2d.AddForce(Vector2.up * jumpPower);
        }
    }

    private void FixedUpdate()
    {
        //left/right movement
        float h = Input.GetAxis("Horizontal");

        //moves player when movement keys pressed
        rb2d.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb2d.velocity.y);

        //limits the players speed
        if (rb2d.velocity.x > maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
        }

        if (rb2d.velocity.x < -maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
        }
    }
}
fervent ermine
#

how do i use the sprite physics shape that is used for tilemap colliders for normal sprites

pearl patio
#

first, why that ?

        //move left
        if (Input.GetAxis("Horizontal") < -0.1f)
        {
            transform.localScale = new Vector3(-0.23f, 0.23f, 0.23f);
        }
        
        //move right
        if (Input.GetAxis("Horizontal") > 0.1f)
        {
            transform.localScale = new Vector3(0.23f, 0.23f, 0.23f);
        }


you should flip the sprite than changing it's scale

upper wedge
#

I tried what you typed earlier but it doesnt seem to use my walking animation

pearl patio
#

and you don't have to put rb2d.velocity in a fixed update, it already use fixed delta time

upper wedge
#

My player doesnt seem to be able to move left

#

I think it could have something to do with

#
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb2d.velocity.y);
pearl patio
#

put a Debug.log (new Vector2("Vector 2 :" + Input.GetAxis("Horizontal") * speed + " rb velocity : " + rb2d.velocity) in update and send the values please when you try to move to the left

upper wedge
pearl patio
#

sorry I misstype
write
Debug.log ("Vector 2 :" + new Vector2(Input.GetAxis("Horizontal") * speed + " rb velocity : " + rb2d.velocity)

upper wedge
#

Have to head to work now

pearl patio
#

oh

#

well I'm dumb
Try that so
Debug.log ("Input :" + Input.GetAxis("Horizontal") * speed + " rb velocity : " + rb2d.velocity)

fervent ermine
#

ok so if i change the sprite in a sprite renderer, how can i get the polygon collider to update to match the custom physics shape of that collider

uneven rune
#

do you know why the collider isn't scaling with it?

#

The arc is it going around a warped collider

#

My code:

#
        Vector2 dir = rb.velocity;
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        if (speed > 0)
        {
            transform.localScale = new Vector3(1 + speed*stretchScale, 1/(1 + speed*stretchScale), 1);
        }```
fervent ermine
#

ok so if i change the sprite in a sprite renderer, how can i get the polygon collider to update to match the custom physics shape of that collider

upper wedge
#

Iโ€™ll try it when I get home tonight, thanks for the help thus far

upper wedge
fervent ermine
#

how do i make it so that a rigidbody2d cannot be affected by other physics objects

#

ok i just set the mass ultra high and that did the trick

meager mural
#

isKinematic

fervent ermine
#

no i still want it to fall and stuff

#

but just not be able to get moved by other physics objects

meager mural
#

Set up layers

fervent ermine
#

eh its fine setting the mass to 10000 worked just fine

meager mural
#

Not the most performant thing to do

craggy kite
#

yeah, shortcuts may come back at you later ๐Ÿ˜‰

uncut sapphire
#

In a 2d game, how would I program a npc to look at the player? I need to figure out specific directions (left, right, up, down). I need to be able to call specific animations based on which way the npc will end up facing.

craggy kite
#

you should check the positions of both for example, then you can determine through math, where the player is.

uncut sapphire
#

I decided to use Vector2 dir = (player.transform.position - transform.position).normalized; in order to find the direction. Though now I'm running into an issue where it is reporting Vector2.left is actually down......2 steps forward, 20 back....

woeful temple
#

can some one help me i wanna trap my cam in a box depending on its size just like treating the cams view area as a collider trapped in a box, how do i do dis?(my game is 2d)

lean estuary
#

You can set it up with Cinemachine

#

It's a built-in functionality

shut trellis
#

Hello...

#

ehmm

woeful temple
#

ohh okay i thot i could get away from not using cine machine oh welp

shut trellis
#

I have a question

#

about my game

woeful temple
#

okay

shut trellis
#

Ok so

#

Today I made a simple pause menu but for some reason, I cant go to the menu

#

I get this error (ignore the warnings)

#

The thing is that I have the Menu in the build settings

woeful temple
#

can isee ur code?

#

did u click d check box??

shut trellis
#

what code?

#

For the Pausemenu?

woeful temple
#

ye

shut trellis
#

ok

woeful temple
#

can i also see ur build settings (sry if i ask to much im not sure how to do it)

shut trellis
#

ok np

woeful temple
#

i know why

#

ur name of d scene and d one ur trying to load arnt d same

#

SceneManager.LoadScene("Menu"); dis is wrong

shut trellis
#

ok

woeful temple
#

in urs its MainMenu

#

Change menu to MainMenu

shut trellis
#

So I should rename it to MainMenu?

woeful temple
#

ye

shut trellis
#

ok thanks

woeful temple
#

Just make sure EVERYTHING is d same when naming scenes

shut trellis
#

yeah ok

#

It works now

median zenith
#
        {
            GetComponent<Animator>().SetBool("Walking", true);
        }
        else
        {
            GetComponent<Animator>().SetBool("Walking", false);
        }
        if (Input.GetKey(UnityEngine.KeyCode.D))
        {
            GetComponent<Animator>().SetBool("Walking", true);
        }
        else
        {
            GetComponent<Animator>().SetBool("Walking", false);
        }``` why does the animation only play when i press A?
median zenith
#

??

tropic inlet
#

you should design that differently

#

replace all of that code with

bool isWalking = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.A);
GetComponent<Animator>().SetBool("Walking", isWalking); 
#

@median zenith

#

|| means or

#

&& means and

upper wedge
#

@pearl patio I just needed to add * Time.deltaTime

pearl patio
#

wait how can this fix your problem

upper wedge
#

I do not know, but I can now walk left and right properly

#
rb2d.velocity = new Vector2(Input.GetAxis("Horizontal") * speed * Time.deltaTime * 2, rb2d.velocity.y);
median zenith
#

ok

#

@tropic inlet thanks

upper wedge
#

So I have

public class Player : MonoBehaviour
{

public int curHealth;
public int maxHealth = 100;

void Start()
    {
        curHealth = maxHealth;
        DeadUI.SetActive(false);
    }

void Update()
    {
            if (curHealth <= 0)
            {
                DeadUI.SetActive(true);
                Time.timeScale = 0;
            }
        }
    }
}
#

It doesnt seem to display the Dead screen when I hardcode the health to 0

lean estuary
#

@upper wedge You IDE would've told you that it doesn't exist in this context.

#

Or you've created a class with faux static SetActive method.

upper wedge
#

Well it is odd because when I set it to 0 it displays the dead screen a couple seconds later once I move my character but it does not set the timescale to 0 I can still run in the background

lean estuary
#

create a field serializable in the inspector, set a reference, then run SetActive on that.

upper wedge
#

I'm not quite sure how to do that exactly

#

I fixed it, sorry

#

It was simply I had the code in the wrong spot

#

But one other thing

#

When I update my

    public int curHealth;
    public int maxHealth = 3;
#

In my script

#

Should I just change it manually?

vocal condor
#

Inspector value overrides the default value; what you set in code as default during declaration.

#

You can hide the value of you do not want inspector modification and it'll be the default since someone/yourself hasn't modify it through the inspector; using the hide tag.

lean estuary
#

usually better using https://docs.unity3d.com/ScriptReference/NonSerialized.html Because you can serialize it, hide it, forget about it, and still use hidden default value. This will remove serialization. Or use internal instead of public to have project wide access without default serialization.

still tendon
#

the error is 'Operator '*' cannot be applied to type 'void' and 'float'

#

on line 13

lean estuary
#

@still tendon Don't cross-post, please.

still tendon
upper wedge
torpid pivot
#

Why not just make the project in 2d

upper wedge
#
private void OnTriggerEnter2D(Collider2D obstacles)
    {
        if (obstacles.gameObject.CompareTag("Traps"))
        {
            curHealth--;
        }
    }

I have this basic code

vocal condor
#

Neither of them are set to trigger mode; isTrigger is false. Neither should be working.

#

Unless you've got some tech-magic occurring, neither should be working @upper wedge

#

Wait, this script is on player... so.. UnityChanThink

#

Should work.

#

Unless your horizontal trigger collider is less than that of your collision collider and prohibits your trigger collider from touching the spike..

upper wedge
#

It must be

#

Iโ€™ll have to try to find a solution

steady idol
#

w0w blob

#

you made that game from scratch?

upper wedge
#

Yup!

#

With the help of some unity assets and a couple of YouTube tutorials for logic

crisp rune
#

is there a SetPixel() type function for tilemaps?

shell wadi
#

https://pastebin.pl/view/942775dc Can I get help please? Im trying to make a matrix, n 2D array for a tetris game
but it wont work
the pieces would appear like 1 million of times at once

upper wedge
#

Any idea as to why?

#

They are both in a canvas

shut trellis
#

Try scaling the heart sprites up and the "stars"

#

Are they in the same canvas?

upper wedge
#

Yeah they are

vocal condor
#

Screen resolution differs.

upper wedge
#

How come everything else stays the same?

vocal condor
#

In other graphics library this is considered extended viewport (last I recalled) and what you'd want is either stretch/shrink or fit viewport (black bars). I don't believe these other types of viewports are natively supported so you'll have to do some fiddling with Camera.orthographicSize or some other means. A quick web search would probably provide plenty of workarounds as I can imagine this situation being quite common.

shut trellis
#

This is my first time getting this error

#

I am not sure what to do

#

I think I need to rename something

vocal condor
#

First time? Good job. It's a pretty common error that is informing you that you're trying to access a member variable of an instance but the instance is null. Your error is pointing to the pipe spawner script and on line 25. Perhaps the variable is null?

shut trellis
#

this is the script

vocal condor
#

So your list is null

#

You should assign it a reference of new list during declaration or start.

shut trellis
#

In line 7

vocal condor
#

This occurred because the list is still null but you're trying to access the Add method.

shut trellis
#

[SerializeField] GameObject pipePrefab = null; // Prefab of the pipe object

vocal condor
#

The list is null according to the error. Unknown if your prefab is as well, with the supplied error; no other errors so highly unlikely that prefab is null.

shut trellis
#

this is the pipe prefab

vocal condor
shut trellis
#

Ok

vocal condor
#

I'm on mobile phone and cannot provide code without great difficulty.

arctic yarrow
#

So, I have written this code to instantiate Obstacles every specific intervals. That's working fine, but, I also want to have the Obstacles have a rotation of either 0 or -90 on the z axis. How could I do it?

craggy kite
#

Put a quaternion.euler on the rotation with your random z rotation @arctic yarrow

fluid geode
#

how do i use this script with tilemaps?

fiery yarrow
#

im working on my character controller:
https://streamable.com/erze6b
but i have issue, it will weirdly jerk the player sometimes.
the platforms are really snuggly together, simple box colliders, they are copypasted so there shouldnt by any offset in their positions. player is using capsule collider. i can show code of anything but im unsure what is relevant to this. movement is simple velocity based rigidbody.
any ideas whats causing it?

craggy kite
#

I guess there is still some weird thing going on with those gabs in there, at least it looks like that.

#

You could checkout combound colliders tho, they may fix that issue, but just a guess @fiery yarrow

fiery yarrow
craggy kite
#

๐Ÿ˜„

#

Love that game honestly ๐Ÿ˜‰

#

I guess you just put like all colliders into one compound? But just wondering, are you not freezing your rb rotation on Z?

fiery yarrow
#

i am

#

but then its my custom character controller so who knows whats wrong with it. (not me for sure)

#

i wasnt touching it there btw its just what it does by itself, no input

#

oh i see adding the composite collider added a rb to the map itself, hence it was falling with my character and freaking out. that makes sense

#

adding this shape collider instead of a capsule works much better, but it makes me wonder why i never saw it used anywhere before and what else might go wrong with it

craggy kite
#

Does making your world rb static work for the level?

fiery yarrow
#

nope, i will have moving parts

craggy kite
#

Okay, lets get away from compound

#

can you show your custom script?

fiery yarrow
#

give me a sec

craggy kite
#

your groundcheck is a trigger?

#

Or is it possible that you are colliding with that little collider on the gaps?

#

and what is this? rigidBody.velocity = new Vector2(x, rigidBody.velocity.y + 0); ๐Ÿ˜‰ like, adding 0, guess just in development ๐Ÿ˜‰

fiery yarrow
#

i turned off my groundcheck and it didnt change it

#

it is a triger

craggy kite
#

Any other trigger inside your player?

#

collider, nto trigger

fiery yarrow
#

no, player has no children with any colliders

craggy kite
#

Or can you just create a very wide collider for this to test, so that your character is really just having issues with the gaps

fiery yarrow
#

yes, i have, it is buttery smooth with a single large collider

craggy kite
#

hm, weird. Can you overlap two boxes and see, if this gives you hikups?

fiery yarrow
#

i tried giving my platforms a bit of an overhang so they overlap into each other, no difference in result

#

or did you mean it in a different way?

craggy kite
#

Nah, i meant it that way. Weird, hard to tell without having your project open: I would just replace my character with like a custom 2d one and check if it still happens there.

fiery yarrow
#

custom 2d one?

craggy kite
#

Just for clarification, your ground things are just box colliders without any rotation, right?

fiery yarrow
#

yes

craggy kite
#

yeah not your own character controller script

fiery yarrow
#

i mean, im literally just giving some horizontal velocity to that rigidbody, and it gets stuck on the edges somehow

#

googling the issues showed many people having similar problems, though none of their solutions have worked for me so far

#

if i give my character a box collider for main with sharp edges, it gets literally stuck. with rounded, it just gets bumped

craggy kite
#

Weird, are you like working in a tiny scale?

fiery yarrow
#

one of those tiles is 1 default unit wide

#

is that bad?

craggy kite
#

No, sounds legit actually. I will try later, gotta take my little one out gettin some fresh air ๐Ÿ˜„

#

Be back later, maybe we can find a solution

fiery yarrow
#

i will keep trying meanwhile. thank you โค๏ธ

ocean drift
#

Hi everyone, I have a question : is there any way to draw a 2D shape directly via Unity, or do I have to create a sprite of said shape in another software before ?

tropic hollow
#
        Collider2D c = Physics2D.OverlapBox(bCollider.bounds.center, bCollider.size, 0, collisionMask);
        if (c)
            print("hit1");

        ContactFilter2D cf = new ContactFilter2D { layerMask = collisionMask };
        Collider2D[] res = new Collider2D[1];
        int resN = bCollider.OverlapCollider(cf, res);
        
        if (resN > 0)
            print("hit2");
fiery yarrow
ocean drift
#

@fiery yarrow sorry I meant in the editor, for example quickly drawing a test map

fiery yarrow
#

well for quick prototyping shapes there is probuilder, you should be able to make just flat 2d shapes with it.
there might be better tools for specifically 2d around

#

i dont think you can easily do it from the editor out of the box, but someone correct me if im wrong

ocean drift
#

Oooh I didn't think about using probuilder

#

Thanks for your answer !

#

I'll look into it

fiery yarrow
#

im not sure if that affects overlaps or just physics simulation itself

tropic hollow
#

@fiery yarrow Ah, i saw that. I'm not using it in a physics simulation so that doesn't matter. But i think i need to find another solution instead of changing default contact offset project wide. Ty anyway!

kind smelt
#

Hi, i'm looking for having all tile position of a tileMap can somebody help me?

upper void
#

so, i have a skeletal animation, but when i added the Sprite Render Flipx thing, it either didn't work, or only did one part of the body

uneven rune
#

Um I think I misunderstand lerp

#

I though that if I were to for say... lerp velocity to 0, 0, 100 by 3 * time.deltaTime it would accelerate to it at 3 per second

#

so what I am currently using is trying to make it follow a player at a certain speed constantly

#

but moving the player away at like 5 m/s with .025 * time.deltaTime as the lerp, it only falls behind to a certain point

#

then it becomes constant

#

What would make it always go to the target at a certain speed but never over?

#

Would I have to just add the direction twards it and clamp it?

#

no...

#

that would only work 1 way

#

hmmmmmmmm

#

Cant beleive I never noticed till now

robust ivy
#

Mathf.Min(3*time.deltaTime, playerSpeed)

#

?

#

just pseudo code but thats the idea

uneven rune
#

im confused

#

so what does lerp do anyway?

#

Is it like if I have .5 it goes half the wayy there?

#

I only started to find out I was using it wrong when I noticed using it to accelerate a character they would slow down faster by reversing direction rather than stop giving it velcoity

robust ivy
#

it move between a and b smoothly, if you using deltatime as multiplier it will move a bit each frame by that much

uneven rune
#

yeah...

#

but Is lerp moving from a to b by a a value?

robust ivy
#

yeah

uneven rune
#

as in 1, 10, 3 would give 4

robust ivy
#

what is 1 10 3

#

and 4

uneven rune
#

or as in 0, 2, .5 would give 1

#

a, b, value

#

gtg be back in 60 seconds

robust ivy
#

if you go to 1 to 10 by 3 it will move by 3 3 3 1

#

or something around that

#

its probably all written in the doc

uneven rune
#

back

robust ivy
#

Description

Linearly interpolates between two points.

Interpolates between the points a and b by the interpolant t. The parameter t is clamped to the range [0, 1]. This is most commonly used to find a point some fraction of the way along a line between two endpoints (e.g. to move an object gradually between those points).

uneven rune
#

ok thats what I though

#

hang on

#

grabbing some code

#

transform.position = Vector3.Lerp(transform.position, followObject.position + offset, initialFollowSpeed);

#

the initial follow speed is .025

#

but as you see

#

well

#

not see

#

but it lags behind a moment

#

then starts coming at the same speed

#

like dampening

#

it starts on back then slows its fallback and starts catching at a certain distance

#

yesysysys

#

iuahg

#

Yeah its not going right

#

it said .5 would return the middle

#

So i have to divide it by the difference between a and b

#

AAARG

#

i mean i got it

#

but still UNITY WHY MUST YOU BE WEIRD

#

nope not working

#

AAAAAAAAARG 2.0f!

robust ivy
#

dont you just need like 0.5f * Time.deltaTime

#

if you have a speed you can just add it to that i think?

uneven rune
#

yeah

#

nooo

robust ivy
#

i suck at math i dont know but thats how ive seen it

uneven rune
#

nonononononoonnoononononon

#

it mean that if every time it returned .2

#

and i had 0 as A and 1 as B

#

then

#

it goes to .2

#

.36 next

robust ivy
#

thing is A will change every frame

uneven rune
#

then .448

#

yeah

#

im counting that

#

it starts 0, then .2, then .46, then .448

#

etc

#

not the 0, .2, .4, .6 I want

#

OK lerp has always done that

#

it doesnt go like (0, 10, .1 ) a, b, interpolation with an output of .1 .2 .3 .4 .5 .6 .7 .8 .9 1.0 1.1...

robust ivy
#

if you want to move just by a certain value why dont you translate or something

#

instead of using lerp

uneven rune
#

had to write a script to calculate for me cause im lazy

#

1, 1.9, 2.71, 3.439, 4.0951 etc

#

thats what the lerp does

#

My original code:

#

transform.position = Vector3.Lerp(transform.position, followObject.position + offset,initialFollowSpeed + (followSpeedByDistance * (transform.position - followObject.position).magnitude) * Time.deltaTime);

#

how would I change the lerp out

hollow crown
#

if you want to use lerp to consistently move towards something then you need to have a start and end position cached

#

otherwise just use MoveTowards

uneven rune
#

ohohoh

#

there is Vector3.MoveTwards

#

I can swap it with that

#

Welp i need a new method for smooth camera movement

#

case movetwards is fiddely

#

so...

#

what can smoothly move a position?

hollow crown
#

Vector3.SmoothDamp

uneven rune
#

cool

#

It has small but noticeable jumps

#

any idea what thats for?

#

Any fix?

#

here lies the resting place of a gif

#

It would have had a longer life but I remembered how strict the admin are about gifs

#

uh

#

Im new at it

#

I just picked a tutorial

#

my first tutorial

#

Anyone know how to fix the jitter issue with smoothDamp? (FIXED)

#

Hey

#

I am using this code:

#
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealth
{
    public float health;
    public float maxHealth;
    public Vector3 healthBarOffset;
    public GameObject healthbar;
}```
#

I am planning on using it to add it into antoher script

#

how do i combine it with another script?

#

I ping u

#

:D

still tendon
#

xd

uneven rune
#

Anyone know?

#

ANYONE

hollow crown
uneven rune
#

sorry ive been waiting 20 minutes

hollow crown
#

you may be using a rigidbody without interpolation and are moving in update

#

it's unclear

uneven rune
#

Fixed that one

#

the one below

hollow crown
#

" combine it with another script" doesn't make sense

uneven rune
#

hang on

hollow crown
#

If you're talking about inheritance, you should watch a tutorial

uneven rune
#

Basicly I want it to look like this:

Settings area 1
Settings area 2

#

so you can open it

hollow crown
#

just make a public variable of your type

uneven rune
#

I have this:

using System.Collections.Generic;
using UnityEngine;

public class EnemyHealth
{
    public float health;
    public float maxHealth;
    public Vector3 healthBarOffset;
    public GameObject healthbar;
}
#

I want thoes variables to be put in another script

hollow crown
#

Just make a public EnemyHealth in your other script

uneven rune
#

It doesnt appear there

hollow crown
#

you need to make your EnemyHealth serializable

#

add [System.Serializable] above it

#

(the class)

uneven rune
#

uh

#

yassss

real pilot
#

any idea why this happens when you create a gradient using SetPixels with a color array?

#

left side should be completely white but turns into red at the end

#

and right side the same but it turns to white

hollow crown
#

I assume your texture's wrap mode is wrong

real pilot
#

you're right, i set it to TextureWrapMode.Clamp and now it works as expected!

#

thanks ๐Ÿ™‚

fervent ermine
#

how can i make a pendulum type thing

#

im trying to make an axe that swings back and forth

light plover
#

does someone know how i make a text stand still, because if i move ma character the text moves with him, but i want it to stay in the speech bubble

white canopy
#

I need help with the trail in Unity 4.12 2019

#

It keeps on overlapping my character

#

Who here can help build a Simple dialog system for NPCs

light plover
vocal condor
#

Consider using object text with text mesh pro and child it to the chat bubble. Else translate the text by getting the world to screen coordinate of the chat bubble and adjusting the text position by that amount; first prefer.

still tendon
still tendon
#

@uneven rune don't make it a class. Make it a method instead. Then you can call it to your main

uneven rune
#

How do I rotate a object by a certain angle?

still tendon
#

Transform.Rotate

uneven rune
#

ok

still tendon
#

for example

#
        transform.Rotate(Vector3.right * Time.deltaTime);```
uneven rune
#

thx

#

How can I get the rotation as a vector3 tho?

#

I want to make knockback on a bullet and need the direction it is going

trim jay
trim jay
#

can anyone help

sweet swan
sweet swan
#

on the ground gameobject

#

should be able to find it at the top of the inspector when you have the ground selected

elfin sandal
#

is it better to use velocity to move in 2D or is it better to use force when a rigidbody is being used?

light plover
tall current
#

@elfin sandal There's good and bad things with both. Velocity is generally better if you want snappy 2D movement (hollow knight esque)

elfin sandal
#

I see

tall current
#

Rigidbody can be good if it's heavily physics-based

#

Velocity skips some physics

elfin sandal
#

does it make it so you don't go max speed when starting to walk with force?

tall current
#

well, force can be more annoying to work with.

#

It adds a force to what you already have.

#

Setting a speed limit can be more annoying that way

#

with velocity it just goes to a set number and stays there.

elfin sandal
#

Isn't there a fixedforce thing?

#

with force mode

tall current
#

Nope, no such thing.

#

You're gonna have to code it in yourself

elfin sandal
#

ohhh

tall current
#

basically check if it's beyond what it's allowed to be. If it is, null that movement vector

#

not null

#

but ya know, 0

spring ledge
#

zero

#

:p

elfin sandal
#

so I have a 2d game that's top down, I want the mouse to move the camera based on the disance of the mouse from the player but when it moves it affects the distance and it's a sporatic camera
what's the right way to do this?

#

should I have it be based on the center of the screen or something?

still tendon
#

From what you described, you have the distance based on the mouse and the camera position.

#

You probably want to use the distance between the mouse and the player object in world space

#

which means you have to get the world space position of the mouse

elfin sandal
#

oh yeah i meant player

#

here's a vid

#

and code

#
mousepos = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
                //Vector3.Normalize(InputLook);
                //print("cam to screen mouse is " + Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue()));
                //print("mouse pos is " + Mouse.current.position.ReadValue());
                //print("normalized input look is " + mousepos.normalized);
                
                lookaheadDir = mousepos - (Vector2)transform.position;
                
                print("mouse being moved mouse dif is " + lookaheadDir);
                LookAheadTransform.position = transform.position + new Vector3(Mathf.Clamp(lookaheadDir.x, -2, 2), Mathf.Clamp(lookaheadDir.y, -2, 2));
                return;```
#

lookahead is where the camera will go

hollow crown
#

You really cannot do it like that

still tendon
#

ok its diff than what I expected, but I think I can try to explain this

hollow crown
#

you should add an offset to your camera based off of the mouse position from the center of the screen

elfin sandal
#

alright

#

would that be viewport?

hollow crown
#

it doesn't matter what space you use

elfin sandal
#

I don't know how to do it

still tendon
#

If you divide the offset by a few (Let's say 5) it will also give you a less 'sensitive' mouselook

elfin sandal
#

the difference?

still tendon
#

the difference (-2 and 2) (i assume) is the min/max

#

but you can make it less sensitive by dividing it

#

after that you can adjust min and max to your preference

#

Replace it with

#

LookAheadTransform.position = transform.position + new Vector3(Mathf.Clamp(lookaheadDir.x, -2, 2), Mathf.Clamp(lookaheadDir.y, -2, 2)) / 5f;
Maybe then you see what I mean

#

if you could make another vid, I can see if there's another thing to focus on. But it will definitely be 'less sporadic'

#

However you might want to expand the limits of -2 and 2 to -10 and 10. But that's some variables that I can't really preview in my head ๐Ÿ˜›

hollow crown
#
Vector2 screenSizeHalf = new Vector2(Screen.width, Screen.height) / 2f;
Vector2 offset = (Mouse.current.position.ReadValue() - screenSizeHalf);
offset = new Vector2(offset.x / screenSizeHalf.x, offset.y / screenSizeHalf.y);
lookAheadDir = transform.position + new Vector3(offset.x * multiplier, 0, offset.y * multiplier)```
That's my random code that I've written entirely in discord
#

it would need clamping too

still tendon
#

Discord needs a specific 'Discode' mode

elfin sandal
#

thanks ๐Ÿ˜„

distant ledge
#

can someone help me with my code?

#

i want to animate the NPC but it doesnt work
just the animation

#

i am using blend trees

hollow crown
#

@distant ledge please do not cross-post.

distant ledge
#

ok

white canopy
#

What would be better for a camera follow player in 2D
Cinemachine
Or
Code the script

tropic inlet
#

Code the script so you know how everything works

white canopy
#

Ok

tropic inlet
#

Relying on someone else's code will be problematic, cuz it might it stop working in subsequent updates

white canopy
#

True

tropic inlet
#

if ur own code stops working due to changes to the API

#

you'll be able to change it easily since you'll have thorough knowledge of your own style and you'll remember what you did

pearl patio
uneven rune
#

How do I make an object rotate towards another?

#

I forgot

#

just point straight to it, no rotate over time needed

meager mural
#

@uneven rune LookAt

uneven rune
#

ok

#

wait

#

how exactly

#

cant find "lookAt"

#

oh

#

googled it

#

found it

#

More complicated question:

How can I calculate the angle to shoot a gun at a moving target? The bullet has 0 gravity, the player has 0 gravity.

#

(static launch speed)

heavy sorrel
#

Hey Iโ€™m trying to make an arena thing where you walk in the camera centers in the room and the doors close behind you until the enemyโ€™s are gone how might I go about that

analog sundial
#

do some know how to make the c# script generate random numbers

#
using System.Collections.Generic;
using UnityEngine;

public class upfast : MonoBehaviour
{
    public float someSpeed;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector2.up * someSpeed * Time.deltaTime, Space.World);
    }
    
}
low lion
#

@uneven rune simple, you just subtract the two vectors. Now you have something that points towards the other vector. You can normalize it and then have a force multiplier

#

Suppose you have two GameObjects

#

GameObject player, GameObject turret (ignore the syntax , it's just pseudo code)

#

vector dir = (turret.positon - player.position).normalized

#

Bullet.rigidbody.addforce(dir* forceModifier);

still tendon
uneven rune
#

@low lion you didn't unerstand the question did you? Shoot it at a moving target

#

the target is moving at a constant rate

#

where do i shoot the 0 gravity projectile

#

Well thats over anyways

#

Heres a different question:

How do i get the rotation of a object as a directional vector3?

#

transform.rotation * vector3.forward does not work

#

neither does transform.forward

#

wait this is 2d code section and im doing 3d

tranquil lava
#

i got quite a small problem. which is, i cant assign sprites to empty objects while running. there are no errors and anything heres the script if youd like to help me

using UnityEngine.UI;

public class HeroCalculation : MonoBehaviour
{
    Vector3 spawnPos = new Vector3(-26, 0, 0);
    string[] heros = {"berserker", "tank", "wizard"};
    public Sprite berserkCard;
    public Sprite tankCard;
    public Sprite wizardCard;

    public void spawn()
    {
        int hero = Random.Range(0, 3);
        Debug.Log(hero);
        GameObject card = new GameObject(heros[hero], typeof(SpriteRenderer));
        card.GetComponent<SpriteRenderer>().sprite = berserkCard;
        card.transform.position = spawnPos;
        spawnPos.x += 4f;
    }
}```
tranquil lava
#

mkay im just hella dumb and forgot to add the sprites to the public sprites

rotund viper
#

oof

#

This chat is a goldmine

hollow loom
#

Hey, which way of doing 2d character platform movement is the best?

rotund viper
#

idk

#

prob a script in the fixed update method

#

and applying force to ridigbody

#

idk im new to unity

#

oh also a ridigbody2d compent and collider

nimble crescent
#

why cant my unity know what RigidBody2D is?

#
{   
    // Start is called before the first frame update
    void Start()
    {
        
    } 

   public Animator animator;
   public RigidBody2D rb;
    .........```
thorn swallow
nimble crescent
#

Yeah, the issue was camelcase :/ lmao

thorn swallow
#

oh haha

#

Yeah that'd do it ๐Ÿ˜›

spring ledge
nimble crescent
#

Yeah I mean Iโ€™m using VS Code

rotund viper
obsidian sky
#

With this

#

hello

rotund viper
#

``a

#

dafuq

#

a

#

oh

#

using it like brackets

obsidian sky
#

Both sides

rotund viper
#

thx ๐Ÿ˜„

#

biggest of thanks

obsidian sky
#

Np :p

thorn swallow
#

If you want to use C# highlighting with it you can do

some text
```
rotund viper
#

a

tight yacht
#
        poly = gameObject.GetComponent<PolygonCollider2D>();
        hitObjects = Physics2D.CircleCastAll(transform.position, shadowCastRadius, Vector2.up, isWall);
        Vector2[] paths = new Vector2[hitObjects.Length * 16];

        for (int i = 0; i < hitObjects.Length; i++)
        {
            if (hitObjects[i].collider.gameObject.GetComponent<ShadowObject>() != null)
            {
                ShadowObject tmp = hitObjects[i].collider.gameObject.GetComponent<ShadowObject>();
                for (int j = 0; j < tmp.objectVerts.Count; j++)
                {

                    Vector2 angleVector = (tmp.objectVerts[j] - new Vector2(lightCaster.transform.position.x, lightCaster.transform.position.y));
                    RaycastHit2D ray = Physics2D.Raycast(lightCaster.transform.position, new Vector2(angleVector.x - 0.0001f, angleVector.y - 0.0001f), rayDistance, isWall); //at the exact pos of the verticy of the object

                    paths[(i * 16) + (j * 4)] = ray.point;
                    Debug.DrawLine(lightCaster.transform.position, ray.point);

                    paths[(i * 16) + (j * 4) + 1] = lightCaster.transform.position;

                    ray = Physics2D.Raycast(lightCaster.transform.position, angleVector, rayDistance, isWall); //at the exact pos of the verticy of the object
                    paths[(i * 16) + (j * 4) + 2] = ray.point;
                    Debug.DrawLine(lightCaster.transform.position, ray.point);

                    ray = Physics2D.Raycast(lightCaster.transform.position, new Vector2(angleVector.x + 0.0001f, angleVector.y + 0.0001f), rayDistance, isWall); //at the exact pos of the verticy of the object
                    paths[(i * 16) + (j * 4) + 3] = ray.point;
                    Debug.DrawLine(lightCaster.transform.position, ray.point);
                }
            }
        }
        poly.SetPath(0, paths);
#

im trying to make a LOS system

#

I can see the lines fine when I debug and it looks correct but the backend, the points are ALL over the place

#

I have no idea y

still tendon
#

can someone help me pleas?

real pilot
hollow crown
inland glen
#

I am trying to move a character and wall jump, but the movement is overriding the x movement. If i dont override, he can gain infinite speed if walking in the same direction. How do i fix this? I did this

#
 public void Move(float horizontal)
    {
        //Add air control
        //Add slip movement and not instant
        if (horizontal<0)
        {
            transform.localScale = new Vector3(-startScale.x,startScale.y,startScale.z);
            
        }
        else if (horizontal>0)
        {
            transform.localScale = startScale;
        }
        //rb2d.AddForce(new Vector2(horizontal*speed,0),ForceMode2D.Force);
        rb2d.velocity = new Vector2(horizontal*speed,rb2d.velocity.y);
        
    }```
#
 public void Jump()
    {
        /*
        if (playerState== WalkingState.Grounded || (playerState == WalkingState.Air && (fowardCheck|| backCheck)) )
        {
            canJump = true;
        }else if (playerState == WalkingState.Air )
        {
            canJump = false;
        }
        */
        if (playerState== WalkingState.Grounded)
        {
            rb2d.AddForce(Vector2.up*jumpForce,ForceMode2D.Impulse);
            canJump = false;
        }else if (playerState == WalkingState.Air)
        {
            if (fowardCheck)
            {
                rb2d.AddForce((-transform.right)*jumpForce*2,ForceMode2D.Impulse);
                Debug.Log("Jumped Wall");
                canJump = false;
            }
        }
        
        Debug.Log($"Jump from {this.name} worked");
        if (canJump)
        {
            rb2d.AddForce(Vector2.up*jumpForce,ForceMode2D.Impulse);
            canJump = false;
        }
    }```
#
 private void FixedUpdate()
    {
        if (_moveAxis.x !=0)
        {
            currentMovement.Move(_moveAxis.x);
        }
        
    }

    void HandleInputs()
    {
        _moveAxis = controls.Player.Movement.ReadValue<Vector2>();
    }
    void HandleJump(InputAction.CallbackContext ctx)
    {
        Debug.Log("HandlerWorked");
        currentMovement.Jump();
    }```
#

I dont know how to fix this

lean estuary
#

@inland glen Use a field variable to collect all of the input, then apply it in one place.

inland glen
#
 public void Move(float horizontal)
    {
        //Add air control
        //Add slip movement and not instant
        if (horizontal<0)
        {
            transform.localScale = new Vector3(-startScale.x,startScale.y,startScale.z);
            
        }
        else if (horizontal>0)
        {
            transform.localScale = startScale;
        }
        //rb2d.AddForce(new Vector2(horizontal*speed,0),ForceMode2D.Force);
         if (Mathf.Abs(maxVelocity2D.x)>=Mathf.Abs(rb2d.velocity.x + horizontal*stepSpeed))
        {
            rb2d.velocity = new Vector2(rb2d.velocity.x +horizontal*stepSpeed,rb2d.velocity.y);
        }
        
        
    }
#

I did this

#

it works

#

but i dont know if its the best aproach

plush fractal
#

Hi everyone, I'm new here - just want to say - good luck for all of your projects and hang in there! ๐Ÿ™‚

fair stirrup
#

You too man!

woeful escarp
#

Hello

atomic patrol
#

hi brothas how do i use IEnumerator and StartCoroutine inside a trigger 2d if it's even possible i mean

craggy kite
#

you call OnTriggerEnter2D and set there your StartCoroutine(Whatever());

uneven rune
#

Anyone know how to calculate the launch angle of a 0 gravity projectile with a fixed speed to a moving target with 0 gravity?

craggy kite
stark trellis
#

Hey Guys ๐Ÿ‘‹ , i just noticed Unity has a CharacterController component, i'm not sure what's the use of that exactly and the docs are not too helpful, do you know any resource with a decent explanation/tutorial? I just want to understand if it's something that can save me some time in handling the character (i intend to use it in a 2d context)

inland glen
#
 groundCheck = Physics2D.BoxCast(
            new Vector2(transform.position.x,
                transform.position.y - (sensorYDistance / 2) -
                (transform.GetComponent<BoxCollider2D>().size.y / 2 * transform.localScale.y) - sensorYOffset),
            new Vector2(
                (transform.GetComponent<BoxCollider2D>().size.x * transform.localScale.x) +((transform.localScale.x > 0) ? -sensorXThicknessReducer : +sensorXThicknessReducer),
                sensorYDistance),
            0,
            Vector2.down, 0, walkable);```
#

i am making a character movement script and the ground check only works when the scale is positve (when the player is moving to the right) and when its negative (the scale value its the same) it doesnt collide with anything but it should

#

the gizmos is copy paste of that and it shows correctly

fringe jay
#

i know its not code but i dont know where this belongs

still tendon
fringe jay
#

now its visible but its really small like 100 times smaller then its in the scene

craggy kite
#

Whats your other sprites z?

blazing tusk
#

is it possible to make a tilemap with stuff like grass that sticks out

fringe jay
#

@craggy kite 1

craggy kite
#

Well I guess, the sprite of the box is just a smaller one than the knob, this is usually being used in the UI for the slider for example, which is tiny. So you should not worry about that until you got your own graphics in, tbh. @fringe jay

fringe jay
#

but the knob is smaller than it is actually

frail dew
#

Uhh

#

so

#

I kinda need help

#

xD

#

so I am trying to make a top down shooter right?

#

so, I made individual sprites for the player holding the gun or knife or whatever

#

How am I able to pickup a knife or gun and then change my players sprite to the right one with the correct gun/weapon feature?

open depot
#

@frail dew there are 2 ways to change sprite do it manual at picki'up/swap weapons by script
or use Animator to change sprite/animation depend of parameters u give him by script

frail dew
#

@open depot could you help me out in dms?

open depot
#

Welcome! Today we're going to set up a 4 way animation system, similar to the movement found in traditional JRPGs, and top down action RPGs. Enjoy!

Tiled: https://thorbjorn.itch.io/tiled

Tiled2Unity: http://www.seanba.com/tiled2unity

Art Assets: https://opengameart.org/content/zelda-like-tilesets-and-sprites

Unity: http://unity3d.com

Abou...

โ–ถ Play video
#

but instead of create movement animations make weapon change

frail dew
#

wuwh

#

how does that make sense?

meager mural
#

Ideally. the gun should be a seperate sprite from the player

#

and you just enable/disable that sprite if you have, or not have the gun

full pilot
#

are there any lessons for 2d code

#

beginner lessons if so

thorn swallow
nimble crescent
#

I need helparu, currently I am doing a testing project to learn what I can about unity. I'm doing the 2d player animation, I have horizontal movement down but vertical is weird. idk how to animate the player based of a launch and when its falling. also when I am moving right in mid air it is battling for control on the animation

#

I currently have to press and hold "S" to get the falling animation since I am using a GetAxis("Vertical")

civic knot
#

Select your object to be able to see the animator transitions at runtime.@nimble crescent

real pilot
#

how can i implement a filling tool like the filling bucket in photoshop/gimp?

#

i'm doing a drawing game with SetPixels() on a texture

civic knot
#

@real pilot look up flood fill algorithms. Might even find some c# code.

real pilot
#

yea doing that right now, thank you ๐Ÿ™‚

atomic patrol
#

Yo bois how can i access light2D intensity from another script :p

tall nova
#

Is there a way I can get my enemy sprite to face in the direction of my player. So far I've used MoveTowards() to get it to follow the player which works great, but it only faces the one direction and that's away from the player sometimes.

thorn swallow
thorn swallow
hearty thicket
#

hello, can someone tell me when OnTriggerEnter2D and Exit2D would be called when game starts? I have some auto detection that works on runtime but doesn't affects when gameobjects are already in level.

#

yeah, I found a workaround. No need for an answer

still tendon
#

how do i turn slides off
so my character stops sliding when i realase a button or the d button

tropic inlet
#

use GetAxisRaw instead of GetAxis

tall current
#

if you're changing the velocity based on the movement from GetAxis, then yeah, do raw

sweet bough
#

my game is a 2d top down pokemon like game using wasd controls and all i have so far is simple left and right movement on my top down gameplay, could someone send me a file for a good 2d top down character controller? if so then ping me.

blazing tusk
#

the ground is a tileset

#

the char has a box collider and a rigidbody2d

fervent ermine
#

is the interita value in rigidbodies like velocity but for spinning?

#

do colliders that are disabled still trigger ontriggerenter2d?

distant pecan
#

3d colliders dont work well with 3d

thorn swallow
livid flare
#

Is there a way to edit the spline of a sprite shape through code?

#

Basically i want to make a floor like hill climb racing

#

and make it random with code

thorn swallow
# livid flare Is there a way to edit the spline of a sprite shape through code?

There definitely is; I'm no expert on the subject but this video talks about it briefly https://youtu.be/Z_FaqmP5Wm0?t=144

In this episode of the Prototype Series - we try to take Unity's latest 2D demo and implement new magical game mechanics to it! โœจ โ˜„๏ธ

โญ Download the project here: https://on.unity.com/2GfTPqP
โญ Check out our longer training session! https://on.unity.com/3ieU81R
โญ You can find the original Lost Crypt demo here: https://on.unity.com/33g9jUn

โ–ถ Play video
livid flare
#

ty ๐Ÿ™‚

thorn swallow
#

Np. he starts talking about it at 2:24

livid flare
#

oh the only reason i didn't find the SpriteShapeController is because i didn't imported the U2D namespace

silver walrus
#

So, I was trying to make a 2D cutscene using Timeline. The cutscene plays just fine after starting the scene from Unity or even if you press the start button on the menu. However, if you load the cutscene, start the GAME scene, return to menu and click on ''Start game'' again, it doesn't play. Why would that be?

robust ivy
#

if you are using static field make sure scripts arent loaded twice when you come back to main menu

analog sundial
#

do someone know how to make a random genrator

#

generator

#

name generator

robust ivy
#

create an array of all your name, shuffle it, take the first ;p

analog sundial
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class namegenerator : MonoBehaviour
{
    public TextMeshPro Text;
    public void BtnAction()
    {
        PickRandomFromList();
    }
    // Start is called before the first frame update
 private void PickRandomFromList()
    {
        string[] students = new string[] {"stijn", "joris", "hakan", "anthony", "poeki", "audrey" ,"baris" ,"natalia" ,"nataniel", "melanie", "asan", "mootje", "izzet", "marvianella", "saoussane", "rumesa","abubakar"};
        string randomName = students[Random.Range(0, students.Length)];
       Text.text = randomName;
    }
}
#

its not working

silver walrus
#

I'm really a beginner, so sorry for any trouble

robust ivy
#

if you load a scene with a script that use singleton and you didnt disable it, it will reload again, having twice the script running, which can break stuff

#

what is not working artem

#

make sure button is linked, that code should work, add debug.log in it to make sure it goes trought

silver walrus
robust ivy
#

no

silver walrus
#

It executes after the last frame

robust ivy
#

the code in the main menu is probably the problem

silver walrus
#

this is the code responsible for the cutscnee

robust ivy
#

MusicScript is a singleton

#

should just google about it

#

there a solution

silver walrus
#

Hmmm I get it, thank you. One last thing, where in the preload scene do i put the script?

robust ivy
#

making sure the script is destroy on awake

#

no idea what is your project or how its build i cant tell

analog sundial
#

do some know how to make random namegenerator

#

need it soo badly

cobalt valley
#

I don't know why but my character can jump more than once while in the background and all because I did the colider, does anyone help?

lusty salmon
#

Hello, what should i do to create a 'spawn area' for my object? I want the objects to be spawned in random position but only on the green area, not the red one.

proud chasm
#

@lusty salmon I recommend doing it by imagining the red part doesn't exist for each axis, so generate a random number between 0 and 2 * the band width for each axis, then add the size of the red area on the given axis if it's greater than the width of the band (but only if the corresponding opposite axis is > the band size, and < the total width - the band size)

#

As for the unity part, I can't help with that

lusty salmon
proud chasm
#

Actually it turns out it doesn't work anyway, my bad, give me a moment

lusty salmon
#

so, basically i need to add several ifs statement?

#

oh, okay

proud chasm
#

@lusty salmon Generate Y coordinate 0 - 560, if it's between [0 and band width] or [560-band width and 560], then generate a random X across the full width (because the x is always in the green in the green here), otherwise, generate a random value between [0 and 2*band width] and add the red width if it's greater than the band width.
A tutorial might be better to follow, but the method here should work if you get stuck

lusty salmon
#

i'll try these two solutions and see which one is easier/perform better. thank you for your time ๐Ÿ˜„

proud chasm
lusty salmon
#

oh wow, is it more simpler that way.

#

but another problem(?), does this work on devices with different screen size? I know i shouldn't hard-coded the size of G.

lusty salmon
#

Finally finished with spawn area, in my opinion using polygoncollider works like a charm

proud chasm
#

@lusty salmon That's good, I realised last night that my answer would be biased towards the middle, woops

lusty salmon
#

Now my goal is to make those enemies shoot a bullet towards the player. ๐Ÿ˜Ž

#

One step closer to finish ๐Ÿ˜€

livid flare
#

Can anyone help me with my 2d car? i finished it but there is a wheel joint bug

livid flare
livid flare
#

so aparently the wheel joints are supposed to be attached to the carbody instead of the wheels

raven badge
#

guys

uneven rune
#

Anyone know why Physics.OverlapSphere is not working

#

if (Physics.OverlapSphere(groundCheck.position, 0.1f, groundLayer).Length > 0)

lean estuary
uneven rune
#

oh

raven badge
#

hi

uneven rune
#

Now it doesnt know what length is lol

raven badge
#

i want my code to reset the scene when i collide with another object

#

but it wont work

uneven rune
#

I would add a debug.log at each step to see which one doesn't work

#

It might also be better to check the tag rather than name

spring ledge
#

@uneven rune OverlapCircleAll

uneven rune
#

thanks

raven badge
#

uhh

#

:((

spring ledge
#

@raven badge I mean

#

Follow the docs

barren tartan
#

can someone help me please ?

#

What I want to have

#

What I have

tranquil lava
#

its because of compression

#

i think

#

but idk how to get rid of it

#

something with exporting the image

feral citrus
#

im making a platformer and i want to see in the editor where my character was like a trial time ghost thing

#

dont need actual functionality for it ingame

#

just to see how to setup objects relative to the movement

tawdry hornet
#

trying to get player movement set up what is wrong with this code?

#

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

public class PlayerMovement : MonoBehaviour
{

public float speed;
private Rigidbody2D myRigidbody;
privte Vector2 change;

// Start is called before the first frame update
void Start()
{
    myRigidbody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    change = Vector2.zero;
change.x = Input.GetAxis("Horizontal");
change.y = Input.GetAxis("Vertical");
Debug.Log(change);
}

}

verbal stag
#

What's it doing? Does it not compile? Does it not behave as expected? If so, how?

tawdry hornet
#

it says error cs1002

verbal stag
#

Sounds like it's not compiling, it doesn't give any more than that in the console?

tawdry hornet
#

error cs1519

verbal stag
#

It usually tells, for compile errors, what line and character caused the issue

tawdry hornet
#

;

verbal stag
#

It's not always 100% correct, but it's usually helpful

#

There

#

You have "privte Vector2 change"

#

I think that typo might be the issue

tawdry hornet
#

ok no more errors

verbal stag
#

Also, I don't think you actually need to declare them as "private"

#

Though there's nothing wrong with doing so

tawdry hornet
#

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

public class PlayerMovement : MonoBehaviour
{

public float speed;
private Rigidbody2D myRigidbody;
private Vector3 change;
private Animator animator;

// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
    myRigidbody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    change = Vector3.zero;
change.x = Input.GetAxisRaw("Horizontal");
change.y = Input.GetAxisRaw("Vertical");
if(change != Vector3.zero);
{
MoveCharacter();
animator.SetFloat("moveX", change.x);
animator.SetFlaot("moveY", change.y);
}
}

void MoveCharacter()
{
myRigidbody.MovePosition(
    transform.position + change * speed * Time.deltaTime
);

}
}

#

is there any spelling errors?

#

or anything wrong with it

verbal stag
#

Yes

#

No

spring ledge
#

Maybe

verbal stag
#

I was right

tawdry hornet
#

its always a mis-spell

verbal stag
#

:p

spring ledge
#

It should tell you thats an error though

#

since Animator won't have a function called SetFlaot

tawdry hornet
#

it did

#

now theres no more errors

spring ledge
#

๐Ÿค”

tawdry hornet
#

thanks

verbal stag
#

Sweet

spring ledge
#

But you said there were no mor eerrors

tawdry hornet
#

before i corrected it

spring ledge
#

I'm confused

verbal stag
#

I said yes first lol

tawdry hornet
#

it told me there was an error so i asked discord and u told me the mis-spell then i corrected it no more errors

verbal stag
#

Inari is just giving me a hard time cause I said I was right

spring ledge
#

but

#

it should ilke highlight the line

#

with red squiggles

#

So you'd know it's that line

verbal stag
#

Ohh

tawdry hornet
#

I use notpad

spring ledge
verbal stag
#

Krugg smash

spring ledge
#

Well still, the error will have like

verbal stag
#

At least use notepad++

spring ledge
#

"yourFile.cs (22,40)"

#

meaning line 22, character 40

tawdry hornet
#

i use notpad on a windows 8.1

#

its not going to tell me if there is a error in my spelling

verbal stag
#

Kk

spring ledge
#

It will, because it won't find a function called that

#

Well Unity will

verbal stag
#

Have fun with that

spring ledge
#

Wiht the line number

verbal stag
#

In the meantime, I have no further intention of being your notepad spell check plugin

#

Peace

tawdry hornet
#

lol

#

cya

thin goblet
#

/giphy //

lilac tangle
#

can anyone help me with this two problem

vocal condor
lilac tangle
#

so i have a puzzle game thats connected to sensor using arduino and it works sometimes but on the other its just lags , i dunno what to do to refresh that specific function so that puzzle pieces lights up
and the second problem is im trying to add audio to puzzle like piano tiles (i have 16 pieces in the puzzle) the idea is that i group the first four puzzle in the array and once one of the pieces is called the a note plays but i dont know how to make it so (if anyone is willing to show the way )

vocal condor
lilac tangle
#

it is a code qn

#

im looking for a code that refreshes a specific function in the code if it takes too long and another code that can activate a function when a attribute from a array is called

vocal condor
#

Is this related to Unity?

lilac tangle
#

yep

#

a puzzle game

vocal condor
#

Is this code portion related to Unity?

lilac tangle
#

wdym?

vocal condor
#

Some folks come in here and say they are working on a Unity project then ask code completely irrelevant to Unity API

lilac tangle
#

is it alright to post a picture?

#

or should i post qn at beginner code

vocal condor
#

code snippet can be posted with back ticks if necessary, else you can post it at hatebin or other code services if too long; such as hatebin.

#

You should post your actual problem and code. If it's a beginner question, go ahead and post it here.

lilac tangle
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO.Ports;
using System.Threading;

[RequireComponent(typeof(AudioSource))]

public class Puzzle : MonoBehaviour
{
    public string piecestatus = "idle";

    public Image A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4,D1,D2,D3,D4;

    public Image A11,A21,A31,A41,B11,B21,B31,B41,C11,C21,C31,C41,D11,D21,D31,D41;

    public Image[] pieces = new Image[16];

    public Image Selected;

    public string COM;

    public Transform edgeParticles;

    public int hello = 0;

    public KeyCode placePiece;

    private SerialPort serialPort;
    private bool serialOK = false;

    public string checkPlacement = "";

    public  AudioSource audioSource;
    public  AudioClip CorrectS;
    public float volume = 1.0f; 

    public Text textBox;
    public float timer = 0f;
    bool Increasetime = true ;


    // Start is called before the first frame update
    void Start()
    {


          serialPort = new SerialPort(COM , 9600, Parity.None, 8, StopBits.One);

          try
        {
            serialPort.RtsEnable = true;
            serialPort.Open();
            serialOK = true;
            Debug.Log("Serial OK");

        }
        catch (Exception)
        {
            Debug.LogError("Failed to open serial port for circuit");
        }

        audioSource = GetComponent<AudioSource>();
        

        //Randomer();
    }```
#

sorry its morethan 2000 characters

#

gimme a sec

vocal condor
#

You could use a coroutine to continuously repeat and wait for an operation but I don't think that's what you're asking for.

lilac tangle
#
    {
        string dataString = serialPort.ReadLine();
        var dataBlocks = dataString.Split(',');

        if (dataBlocks.Length < 8)
        {
            Debug.LogWarning("Invalid data received");
            return;
        }

        int AState, BState, CState, DState, EState, FState, GState, HState;

        if (!int.TryParse(dataBlocks[0], out AState))
        {
            Debug.LogWarning("Failed to parse AState. RawData: " + dataBlocks[0]);
            return;
        }
        if (!int.TryParse(dataBlocks[1], out BState))
        {
            Debug.LogWarning("Failed to parse BState. RawData: " + dataBlocks[1]);
            return;
        }
        if (!int.TryParse(dataBlocks[2], out CState))
        {
            Debug.LogWarning("Failed to parse CState. RawData: " + dataBlocks[2]);
            return;
        }
        if (!int.TryParse(dataBlocks[3], out DState))
        {
            Debug.LogWarning("Failed to parse DState. RawData: " + dataBlocks[3]);
            return;
        }
        if (!int.TryParse(dataBlocks[4], out EState))
        {
            Debug.LogWarning("Failed to parse EState. RawData: " + dataBlocks[4]);
            return;
        }
        if (!int.TryParse(dataBlocks[5], out FState))
        {
            Debug.LogWarning("Failed to parse FState. RawData: " + dataBlocks[5]);
            return;
        }
        if (!int.TryParse(dataBlocks[6], out GState))
        {
            Debug.LogWarning("Failed to parse GState. RawData: " + dataBlocks[6]);
            return;
        }
        if (!int.TryParse(dataBlocks[7], out HState))
        {
            Debug.LogWarning("Failed to parse HState. RawData: " + dataBlocks[7]);
            return;
        }
        Debug.Log(dataString);```
#
    {
      if (serialPort.IsOpen == false)
      {
          serialPort.Open();
      }
      if ( A1.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1) && A2.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1) &&
      A4.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1) && A4.GetComponent<SpriteRenderer>().color != new Color(1,1,1,1)){
      serialPort.Write("1");
      serialPort.Write("5");
     
        }
if(hello == 0 ){
if(a == 1 && g == 0){
A1.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
//Instantiate(edgeParticles , C1.transform.position, edgeParticles.rotation);
A11.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
   
}
if(b == 1 && h == 0){
  A2.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
  //Instantiate(edgeParticles , C2.transform.position, edgeParticles.rotation);
  A21.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
    
            }
if(c == 1 && e == 0){
  A3.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
  //Instantiate(edgeParticles , C3.transform.position, edgeParticles.rotation);
  A31.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
     
            }
if(d == 1 && f == 0){
  A4.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
  //Instantiate(edgeParticles , C4.transform.position, edgeParticles.rotation);
  A41.GetComponent<SpriteRenderer>().color = new Color(0,0,0,0);
     
            }
}```
#

i did this part for each row for the puzzle

#
    {
      if (serialPort.IsOpen == false)
      {
          serialPort.Open();
      }



      pieces[0] = A1;
      pieces[1] = A2;
      pieces[2] = A3;
      pieces[3] = A4;
      pieces[4] = B1;
      pieces[5] = B2;
      pieces[6] = B3;
      pieces[7] = B4;
      pieces[8] = C1;
      pieces[9] = C2;
      pieces[10] = C3;
      pieces[11] = C4;
      pieces[12] = D1;
      pieces[13] = D2;
      pieces[14] = D3;
      pieces[15] = D4;

      Selected = pieces[UnityEngine.Random.Range(0,pieces.Length)];
      Selected.GetComponent<SpriteRenderer>().color = new Color(1,1,1,1);
      Debug.Log(Selected);
      if(Selected == A1 || Selected == A2 || Selected == A3 || Selected == A4){
        serialPort.Write("1");
        serialPort.Write("5");
      }
      if(Selected == B1 || Selected == B2 || Selected == B3 || Selected == B4){
        serialPort.Write("2");
        serialPort.Write("6");
      }
      if(Selected == C1 || Selected == C2 || Selected == C3 || Selected == C4){
        serialPort.Write("3");
        serialPort.Write("6");
      }
      if(Selected == D1 || Selected == D2 || Selected == D3 || Selected == D4){
        serialPort.Write("4");
        serialPort.Write("8");
      }
      if(Selected == A1 || Selected == B1 || Selected == C1 || Selected == D1){

      }
    }```
#
      if(Selected == A1 || Selected == B1 || Selected == C1 || Selected == D1){
        if(e == 1){
          StartCoroutine(waitThreeSeconds());
          //Randomer();
        }
      }
      if(Selected == A2 || Selected == B2 || Selected == C2 || Selected == D2){
        if(f == 1){
          StartCoroutine(waitThreeSeconds());
          //Randomer();
        }
      }
      if(Selected == A3 || Selected == B3 || Selected == C3 || Selected == D3){
        if(g == 1){
          StartCoroutine(waitThreeSeconds());
          //Randomer();
        }
      }
      if(Selected == A4 || Selected == B4 || Selected == C4 || Selected == D4){
        if(h == 1){
          StartCoroutine(waitThreeSeconds());
          //Randomer();
        }
      }
    }

    IEnumerator waitThreeA(){
      //hello = false;
      yield return new WaitForSeconds(3);
      //print("A");
      hello = 1;
       
    }
    IEnumerator waitThreeB(){
      //hello = false;
      yield return new WaitForSeconds(3);
      //print("B");
      hello = 2;
        ;
    }
    IEnumerator waitThreeC(){
      //hello = false;
      yield return new WaitForSeconds(3);
      //print("C");
      hello = 3;
        
    }
    IEnumerator waitThreeSeconds(){
      //hello = false;
      yield return new WaitForSeconds(3);
      print("BOOOM");
        //hello = 1;```
#

i did use coroutine but its still lags

vocal condor
#
string dataString = serialPort.ReadLine();
var dataBlocks = dataString.Split(',');
int state;

if (dataBlocks.Length < 8)
{
    Debug.LogWarning("Invalid data received");
    return;
}
for(int i = 0; i < dataBlocks.Length; ++i)
{
    if (!int.TryParse(dataBlocks[i], out state))
    {
        Debug.LogWarning($"Failed to parse state[{i}]. RawData: {dataBlocks[i]}");
        return;
    }
}
Debug.Log(dataString);
```Edited: Updated
lilac tangle
#

ok

#

so the code u posted is to replace the void serial read right

vocal condor
#

Not entirely sure if it can supplement but definitely an optimization improvement over what you had before.

lilac tangle
#

ok thank u

vocal condor
#

I've got to go though, good luck.

verbal stag
#

Holy lack of pastebin, batman!

tawdry hornet
#

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

public class PlayerMovement : MonoBehaviour
{

public float speed;
private Rigidbody2D myRigidbody;
private Vector3 change;
private Animator animator;

// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
    myRigidbody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    change = Vector3.zero;
change.x = Input.GetAxisRaw("Horizontal");
change.y = Input.GetAxisRaw("Vertical");
UpdateAnimationAndMove();

}
void UpdateAnimationAndMove()
{
if(change != Vector3.zero);
{
MoveCharacter();
animator.SetFloat("moveX", change.x);
animator.SetFloat("moveY", change.y);
animator.SetBool("moving", true);
}
else
{
animator.SetBool("moving", false);
}
}

void MoveCharacter()
{
myRigidbody.MovePosition(
    transform.position + change * speed * Time.deltaTime
);

}
}

#

what is wrong with this code

#

ive downloaded a new coding app to help me figure it out but its not working

rocky vault
#

@tawdry hornet In the case of moving character I always use
transform.position += change * speed * Time.deltaTime
or
transform.position -= change * speed * TIme.deltaTime
I or big youtuber (as I saw) not use rigidbody.MovePosition

tawdry hornet
#

there is a error telling me there is something wrong with a }

rocky vault
#

@tawdry hornet you write a ";" after an if in UpdateAnimatorAndMove()

#

remove this ";"

#

if(change != 0);

should not a ";"

#

@tawdry hornet

tawdry hornet
#

o

rocky vault
#

I usually get error in Vs Code

#

By making a new script

#

of your code

tawdry hornet
#

now there is 2 errors

rocky vault
#

what are they saying

tawdry hornet
#

wait now 1

#

Assets\Scripts\PlayerMovement.cs(26,29): error CS1002: ; expected

rocky vault
#

no erros

#

in my editor

tawdry hornet
#

try to upload the script to unity

#

then it might tell you the error

rocky vault
#

no

#

it's not throwing any errors

#

i tried in unity

tawdry hornet
#

huh

#

send the code?

rocky vault
#

This is @tawdry hornet

tawdry hornet
#

ok 1 sec

#

ok cool it works now

#

wait

#

1 problem acctullaly

#

my walk movements dont work

#

i think thats somthing with my animator

#

tho

raven badge
#

I'm trying to reset the scene whenever i collide with the enemy, i made sure to tag the enemies and the player, but even so, the scene does not reset when i collide with the enemy.. i have also tried to use the Enter method but it gives me a red error saying something about permeators or something

silver walrus
#

@raven badge can you copy the code please?

raven badge
#

ah i got it to work

#

@silver walrus thank you though

silver walrus
#

np, feel free to ask for help tho

midnight basalt
#

I want to get the sprite of the tile that my ray has collided with and I currently have this code;

RaycastHit2D hit = Physics2D.Raycast(Aim.position, Aim.up, reach, blockMask);
if (hit.collider != null)
{
    sr.sprite = collided tiles sprite;
}
#

but I doubt if that is possible with this code

#

if not is there any other way I could get the Tile I've collided with?

#

or should I use game objects and get their sprite instead

tropic inlet
#
hit.collider.gameObject.GetComponent<SpriteRenderer>().sprite
#

oh u said tile

#

idk much about 2d tbh
but if it were gameobjects, it would be easy

still tendon
#

Why do I get an error in this? everything in Unity matches up. I am making a ground check for jumping I put error to show it does't have the *s

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

public class groundcheck : MonoBehaviour
{
    GameObject player;
    // Start is called before the first frame update
    void Start()
    {
        player = gameObject.transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update()
    {
        
   
    
    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Ground")
        {
          **  player.GetComponent<playermovement>.isGrounded = true;**
        }

    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.collider.tag == "Ground")
        { **player.GetComponent<playermovement>.isGrounded = false;** }
            
    }


}
hollow crown
#

GetComponent<Type>()

#

missing the brackets that make it a method

still tendon
#

thx

neat crypt
#

Hey everyone! How can I make a "Rain" of objects? For example there is an infinite spawn of bullets on the sky above you. The objects "bullets" will be falling in a specific velocity. And when they are not visible just deactivate/destroy them. Ping me if there's some tutorial that can help me ๐Ÿ˜„

ornate lava
zinc valley
#

anyone know of a way to get a 2d character to collide with 3d objects in a perspective view (not 2d)

plush coyote
#

3d collider..

zinc linden
thorn swallow
# zinc linden Heyo! https://www.codepile.net/pile/7AkLZ6GX I got an issue I'd like to somehow ...

Make an array for your correct answers, and then make a progress integer (start at 0, if they get one correct, increment it by one)
Then all you need to do is check if their input matches the result in the array at the progress index

private int samples[] = new int[] {0, 3, 5};
private int progress = 0;

public void SamplesCheck(int nr)
{
  if (nr == samples[progress])
  {
    //Advance progress
    progress ++;
  }
  else
  {
    //Reset progress
    progress = 0;
  }
}

Unless you need booleans for a specific reason, this is a much simpler way to do it

#

Then check if the progress integer is high enough to open the door

wooden acorn
#

i can't understand why my character moves faster diagonally, how is that happening?

#
moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * speed;
rb.MovePosition (rb.position + moveVelocity * Time.fixedDeltaTime);```
mystic veldt
#

Ah something I can actually help with. When you apply forces in both directions, the resulting force is larger than if you applied it only one direction.
If you draw a triangle where both sides are 1, what is the value of the diagonal?
sqrt(2) which is > 1.

#

The result is that when you move diagonally, you move faster due to the magnitude of the combined forces.

#

@wooden acorn

wooden acorn
#

i need to normalize it, right?

#

i normalized and it worked, thank you so much!

#

c:

mystic veldt
#

Yep!

burnt mural
#

Why doesn't this work

#

I want my monster to die if its z rotation is 180, (if hes on his head)

#

I dont get any errors it just doesnt work

robust ivy
#

it has to be 180 flush, no floating numbers

west badge
#

also, remember that Rotation is not a Vector3

terse thorn
#

can someone tell me how i made a object ALLWAYS point towards anothe in a top-down perspective?
(C#)

trim jay
#

can any one help with my main menu? When ever i hit PLAY it acts like its about to switch a scene but it doesn't.

#

nvm i got it

icy agate
#

Anyone experienced with Unity able to help me make pixel art show up properly?

civic knot
trim jay
#

i just needed to fix the script thx tho @civic knot

#

oh and thx for sending me the link for the beginner guide for unity.

autumn ice
#

u need to build settings accoring toyour order

waxen sorrel
#

Does anyone know if it's possible to tie a sound file to a specific type of tile in tilemaps?

#

Never mind, I figured it out

distant pecan
still tendon
#

@lilac tangle bruh thats a lot of if statements, also hard to read what your trying to do

your veribles make no sence its gunna take up a bunch of memory

can seperate bits in to
methods or use return types to simplify what ever it is your trying to do try not to use so many if statements
....

i say if a script causes you to lag theres a better way to do it

try not to leave debug statements or exceptions in your scripts

#

cache the sprite renderer instead of getting objects component each time

#

nvm bru

#

id be here for ages....

#

why dose checker have so many perams..

#

a b c d e f g says nothing of what it dose

outer helm
#

i finished a UI game and the canvas size is 4:3 and its all working and stuff but when i build the game, the text doesnt show up. help?

still tendon
#

check order of gameobjects i think it renders it based of priority top most important bottom least if not try other way round

think like photoshop layers

outer helm
#

oh worked ty

prime junco
#

is there a built in way to set up animations with multiple orientations depending on a condition? Like I've been using the animator flow chart, but it seems unintuitive to have to have a block for every different angle for every cycle, and have them all connect depending on conditionals

still tendon
#

you doing a top-down game?

#

cant really have more than 2 orientations in a platformer... just guessing

#

have a look at blend trees

#

not sure thats what you mean but it cleans up the grapth a bit..

#

i think 2d freeform on blendtree is what you mean you can set multiple clips in run from the single blend tree set it to blend between animations based on the slider value
iv its pritty easy to setup 2dfreeform with a controller...

image from docs

#

not sure tho...

prime junco
#

it's for the main player

#

I have 4 different orientations each with their own animations

#

I'll take a look

prime junco
#

but the problem is that I have multiple idle orientations

#

how can I change which idle orientation is used depending on the blend tree direction it came from? (e.g walk left > idle left)

lavish canyon
#

I'm trying to do a vision cone with a custom mesh and Raycast but when i call the code to set the origin to the enemy position in the update of the enemy it doesn't work. Does anyone know how i could try and fix it? If i move the origin by a vector with the x and/or y increasing by 1 it works.

kind tiger
#

Me and my friend are trying to make an minecart type game using splines. We have run into issue with our current asset and was wondering if anyone knew a better one. We were pairing our spline asset with the sprite shape renderer/controller to generate the track, but I think there is just to much different between the asset and how the sprite renderer handles points. Is there an asset out there that does both what the sprite render does and has script that handle the following/rotation?

terse thorn
#

can someone tell me how i made a object ALLWAYS point towards anothe in a top-down perspective?
(C# unity)

lavish canyon
#

I'm trying to do a vision cone with a custom mesh and Raycast but when i call the code to set the origin to the enemy position in the update of the enemy it doesn't work. Does anyone know how i could try and fix it? If i move the origin by a vector with the x and/or y increasing by 1 it works.

prime junco
#

i'm doing a top down 2D game - how should I handle layering so that objects an object higher on the screen than another appears above it, while an object lower than another appears below?
what I tried was setting the z of the object to the y level, though since the camera follows an object it doesn't work

civic knot
prime junco
#

how can I tint my sprite white?

civic knot
#

SpriteRenderer.color = Color.White or something.

waxen sorrel
#

How do I properly code changing music when I enter a certain zone on the map? Currently I have a composite collider tied to a tilemap and when I enter/stay in it - the music changes and then resets to default when I leave. However for some reason it keeps changing between two tracks while I'm still inside the collider?

#

This is one composite collider I can stay inside and the music should be the same when I'm inside, but it keeps switching back and forth if I move

waxen sorrel
#

Any ideas? .-.

thorn swallow
# waxen sorrel Any ideas? .-.

OnTriggerStay is triggered once per physics update. If you only want it to change once you should probably use OnTriggerEnter

waxen sorrel
#

Yeah, I tried that - didn't work

#

We figured out that it was a problem with composite collider - somehow it only worked when I was standing exactly on the border of it. If I left the border - it was as if I left the whole collider, the concept of inside/outside didn't exist. I switched it off and everything worked perfectly fine.

uneven rune
#

An I am trying to make it so that it grabbs it from where you click

#

not the greatest

#

Does anyone have an idea as how to do it?

#

I think i know a way...

#

i need to get a position, and fix the rotation

#

So how can I get a position with the rotation undone

#

if I can get that i can just do the rotation multiplied by the offset to get it

#

So main question:

How to get a position, and remove the rotation from it?

uneven rune
#

I am using very sus code

#

so close to correctly grabbing it

#

nooo it deleted my gif

#

I am free

proper glacier
#

hey! how would i go about calculating a recttransform's position with another anchor, like unity editor does automatically when you change the anchor?

atomic patrol
#

how can i detect in another script if that collider of that prefab hitted something

open kindle
#

Hi ! I am currently testing addressables, I was wondering if it is respecting playersettings > quality > Texture Quality, when building the bundle for a specific platform or if it is copying the file depending on the max size in the texture properties. Did not find a way to inspect the bundle, so not sure of the result

icy agate
#

Anyone know how I can get 2d pixel art to show up without imperfections? I've gotten close but there always seems to be imperfections in the art.

#

I'm trying to get the art in Unity to showup exactly how it does in paint but can't seem to get rid of thee black dots and line imperfections.

kindred fractal
#

2d-code, uhm, well, i would need some help.

I have a "working" chunk system, and they can be loaded, and now im working on the onload functions, and yeah:

foreach (int i in WorldChunks) {
            if (i == 1 && Vector2Int.Distance(new Vector2Int(PlayerChunkX,PlayerChunkY), i need the coords of i here) >= SettingChunkUnloadDistance) {
                UnloadChunk(THE COORD.X of i, THE COORD.Y of i);
            }
        }

WorldChunks is a 2D array, and a "coordinate" could be either 0 (unloaded) or 1 (loaded);
PlayerChunkX and PlayerChunky is a coord in the WorldChunks array;

i found out that a foreach can be used to find every "chunk that is loaded" aka a 1, but uhhh
in that code snippet i basically just wrote in what i would like to ask for help how to get. the coords of "i"

yeah im not a pro tbh, i can get stuck very often because of my lack of knowledge

lean estuary
#

@icy agate Pixel art has to be pixel perfect for the orthographic camera correct size for the current resolution. There's pixel perfect package in the manager for that and/or research pixel perfect implementations.

pearl sail
#

I am making a digital board game in which the 4 players around the board have hands of cards. I would like it so that, if a player has an empty hand, the camera will dynamically zoom in, as the extra space for the hand is no longer needed. I have taken some screenshots of this.

https://imgur.com/a/n75LMnE

As you can see in the second image, the bottom player no longer has any cards. As you can see in the third image, I have drawn a red rectangle around where the camera should be as a result of this.

What would be the best way to accomplish this? I think it might have something to do with the camera "clamping" feature, but not sure.

Complicating the matter further is that I want the camera to also rotate depending on which player's turn it is (so that whoevers turn it is always has their hand at the bottom of the screen). This results in a lot of permutations of possible camera rotations, positions, and zoom level.

Basically, I would like to be able to set 4 values (the edges of a bounding rectangle) and have the camera always adjust to those bounds.

slate epoch
#

Hey guys I wanna know if anyone of you can help me in something. I want to make my character move it's face towards the mouse, I can't figure out how to do it. I can attach images if you don't understan what I mean

tropic inlet
#

So, you want to rotate a 2d character towards the mouse

#

that's a common question

#

if only I was good at math, then I would be able to remember off the top of my head
the solution involves using Atan

#

ok, there we go

#

atan2(y, x) gives you the angle in radians
then * Mathf.Rad2Deg converts it to degrees

#

@slate epoch

slate epoch
#

I'm sorry for answering late

#

Ty for your answer but that's not what i meant. I know it's a little confusing tho.
Is like I want to make a sprite orbitate a point, but the sprite not changing it's rotation

#

this might be an example

#

like the earth "sprite" is not rotating, but the object is orbiting

#

sorry for the mess ๐Ÿ˜“

rocky vault
#

Guys I have a problem