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

1 messages ยท Page 34 of 1

wraith linden
#

i'll do that then

snow willow
#

Just make sure you don't have duplicate scripts or anything

wraith linden
#

I didn't

#

but it still doesn't work!!

#

the box is created and I can see it but it doesn't stop me from seeing outside it

snow willow
#

you need to figure out that warning

#

See this?

#

See where it says "Script"

#

and it's grayed out

wraith linden
#

yeah

snow willow
#

above your Camera Bounds

#

delete that

#

that's a broken script reference

#

and if you keep getting that warning, you have more of those in your project

wraith linden
#

okay i deleted it but no fix to the error

#

oh okay

snow willow
#

are there more errors in the console

#

when you play the game

wraith linden
#

not that i see

snow willow
#

when the game is running?

wraith linden
#

(it's running btw)

hollow crown
#

You do have errors disabled, but it appears like there are none anyway

snow willow
#

ok and - what isn't working?

hollow crown
snow willow
#

Yeah deffo turn errors on

#

but what isn't working now?

wraith linden
#

the camera isn't abiding by the bounding box

snow willow
#

hmm - and you only have one camer ain the scene right?

#

Can you sahre your CameraFollow script?

wraith linden
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamFollow : MonoBehaviour
{

    public Transform followTransform;

    [SerializeField] CameraBounds2D bounds;
    Vector2 maxXPositions, maxYPositions;

    void Start()
    {
        bounds.Initialize(GetComponent<Camera>());
        maxXPositions = bounds.maxXlimit;
        maxYPositions = bounds.maxYlimit;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 currentPosition = transform.position;
        Vector3 targetPosition = new Vector3(Mathf.Clamp(followTransform.position.x, maxXPositions.x, maxXPositions.y), Mathf.Clamp(followTransform.position.y, maxYPositions.x, maxYPositions.y), currentPosition.z);
        this.transform.position = new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z);
    }
}
snow willow
#

this.transform.position = new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z);

#

this line doesn't look right

#

should be this.transform.position = targetPosition; or something

#

right now it's ignoring all the bounds calculations that you're doing to get targetPosition

wraith linden
#

Thank you!!!

snow willow
#

or rather - this.transform.position = new Vector3(targetPosition.x, targetPosition.y, this.transform.position.z);

wraith linden
#

your a savior

#

finally!!

#

okay so i'm trying to get this to work with Cinemachine but it wants me to create an empty game object with a box collider and rigidbody2D

#

this causes my character to get pushed out of the area, is there a way to fix this?

crystal geode
#

is it possible to change a box collider in sync with an animation loop?

crystal geode
#

oop, nevermind, I found it

#

different question

#

how can I pause my animation at a particular point to edit the collider?

#

selecting different keyframes doesn't do anything while the animation is paused, and if I try to pause during the animation, then the object just reverts to its default sprite

snow willow
#

You can just scrub through the animation clip manually

crystal geode
#

that's what I'm doing

#

I think the problem is that my sprites aren't split correctly

#

my object shows as having the entire sprite sheet as its sprite

#

rather than individual ones

#

no matter what frame of the animation its on

#

oh wait I'm dumb

#

nvm, fixed it

crystal geode
#

is there a way to shave off the last 'tick' of animation at the end of a loop? I'm setting my last key frame to the same thing as my first one so that the pose before it can hold as long as I need it to, but the last key frame adds a little bit more animation that makes the first pose last longer than I want

barren lark
#

Yeah, usually you just shorten it by a single frame

#

No wait

#

Keep it, but move the end marker back by a frame if you can

#

That's what I do in blender for smooth looping animations

limber lichen
#

Hi i spoke to some one last night but i still cant get my ai to face the player on trigger. Can any one see somthing wrong with my script

#

this is what i tried with the LookAt Method

knotty barn
limber lichen
#

@knotty barn thank you sorry only joined last night ill post it in there, thanks

remote moth
#

How can i create a chunk system?

limber thistle
#

@remote moth What do you need it for?

#

@still tendon What problem do you currently have with that?

remote moth
#

to make the world infinity long, need i chunks

undone coral
#

Guessing you'd save those 'chunks' as prefabs, and instantiate them when needed.

remote moth
#

is there an alternative to chunks?

undone coral
#

That'd depend how your terrain generator works, and what you mean by chunks exactly.

remote moth
limber thistle
#

For an infinite world, you need a generator that can generate chunks one bye one, instead of the whole world in one go. The problem is usually to keep the boundary between chunks consistent

#

Then you create new chunks of the world as needed

undone coral
#

Don't cross post, please. :p

knotty barn
#

@tribal gyro Yea don't cross post.

marble badger
#

collisions.above = directionY == 1;
can anyone tell me how does the relation and assignment work her

#

here

undone coral
#

collisions.above (a bool) is set to the outcome of (directionY == 1), which returns a bool.
So collisions.above becomes true if directionY is 1.

marble badger
#

got it

undone coral
#

In other words...
= set to
== equals

marble badger
#

can i use transform.translate with Vector2 with no issue for a 2D platformer game

gaunt tulip
undone coral
marble badger
#

can i use transform.translate with Vector2 with no issue for a 2D

snow willow
snow willow
#

you can't have a space before it

gaunt tulip
#

i just deleted the file and started again ๐Ÿ™‚ it was only a few lines so it was fine @snow willow

#
public class Enemy_Follow : MonoBehaviour
{
    // Start is called before the first frame update
    public float speed;

    private Transform playerPos;

    void Awake()
    {
        playerPos= GameObject.FindGameObjectWithTag("Player").transform; (TH)
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime); (TH)
    }
}
``` what does this code do , ESPECIALLY CONFUSED WITH THE PART WITH (TH) , all i have understood is that players position is equal to the object with the player tag position and  yeah thats pretty much it
marble badger
#

in the first TH you find a gameobject with the tag named "Player" and assigned it's position to playerPos variable

#

to be specific the transform

#

in the 2nd TH you changed the position of the current object the script is attached to. To the position of the gameObject with Player tag

#

in the 1st Th to get the position you need to say
playerPos= GameObject.FindGameObjectWithTag("Player").transform.position;

swift bridge
#

Hello there. I am having a question regarding SpriteMask overlapping. On the image I have 3 objects:

  • The tall grey rectangle, that has SpriteRenderer & SpriteMask with the same sprite.
  • The 2 "crack" SpriteMasks.
  • The wide black rectangle.

The gray sprite is set to "visible outside of the mask", so it is transparent at the cracks. The same object's mask (the orange outline) is set on a custom range so it doesn't affect the gray area.

My problem is that I don't know how to make the black rectangle to be shown only within the gray mask (which it current is, the hidden parts are outlined in blue), **and ** to be transparent on the cracks (which it currently isn't, the desired transparency is outline in red). In other words, I need the black area to be visible inside one mask (the gray), and outside of another one (the cracks).

gaunt tulip
limber lichen
#

Hi, Anyone know a good tutorial on how to create a fog effect for 2d top down please?

keen solar
#

Hello, Im having a bit of trouble with making 2d platforms. Im using a prefab, but when it is created in game, im getting some sort of sliding motion

blissful gale
#

add a physics material to your players rigid body and set the friction to 0 @keen solar

keen solar
#

Thanks

hidden quarry
#

I'm creating a RawImage using a Material based off the Hidden/BlitCopy Shader and set its _MainTex to a RenderTexture. This RawImage is then displayed in a Canvas. This works fine, but when I try to replace the _MainTex with a new one after initially having set one my displayed rawimage just becomes black. The only workaround I found is creating a new Material. Am I missing something?

hidden quarry
#

Found it, SetMaterialDirty is what I missed ๐Ÿ‘

fathom niche
#

I have this problem where despite having setup OnEnterCollision2D events they never trigger for some reason, i've added box 2d colliders (for reference im checking for collisions on a bunch of prefab clones all in the same parent)

azure aurora
fathom niche
#

no, though ive tried re-writing as triggers and no dice :(

azure aurora
#

Hmm

#

And what if you don't give them any parents in common ?

fathom niche
#

i have not tried, though organisationally that will look horrible

#

i will now thanks

azure aurora
#

Well, we're testing

#

Also

#

Do your objects have 2D rigidbodies ?

fathom niche
#

i have tried with and without rigidbodies and nothing

azure aurora
#

The 2D ones, right ?

fathom niche
#

yeah

azure aurora
#

Can you screenshot the inspector for your object ?

fathom niche
#

this is literally my first project so don't judge if i've done something stupid

azure aurora
#

Did you try changing static to dynamic

#

No judgement, don't worry

#

we're all learning here ^^

fathom niche
#

oh it works now

#

tysm

azure aurora
#

Nice ^^

#

Do you happen to know how to make it so that my camera shows the same things when changing the size of the screen ?

#

I have this button on screen that isn't correctly shown when going full screen

#

It's ok if you don't know ^^

knotty barn
#

Canvas scaling should deal with that

#

Just need to make sure your anchors are set up correctly

azure aurora
#

Oh right, I'll check that. I'm not really used to canvas ^^

#

Thanks

#

Oh, I found my error, it was that I set the game aspect ratio to free aspect

knotty barn
#

@azure aurora That is not the error, it just allows you to see the issue

#

Undocking the game view in free aspect and resizing it is a good way to see how it will behave on various screens

azure aurora
#

Ah, I see

#

Well, it seems like a complex problem to handle. I'll deal with that later in developpement

wet glen
#

i have already asked before but after trying for like 1 hour i still did not get out: how do i make my game work with other espect ratio's?

tropic charm
#

@wet glen If your camera is orthographic then you can use a script like this to (in the case of this particular script) force the camera to match a specific aspect ratio by adjusting its orthographicSize size property.

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

public class SetupCamera : MonoBehaviour
{
    [SerializeField] float _initialSize = 5.0f;
    [SerializeField] float _targetAspect = 1.777778f;

    void Update()
    {
        float newSize = _initialSize * (_targetAspect / Camera.main.aspect);

        if (newSize != Camera.main.orthographicSize)
        {
            Camera.main.orthographicSize = newSize;
        }
    }
}
wet glen
#

yes it is orthographic

#

what shood _targetAspect ? be shood that be 1920/1080?

#

o wait it already is

tropic charm
#

Yes, that was for a game designed for a 16:9 aspect ratio.

#

You don't get black bars though. That is, on a 4:3 display, you will see whatever is above and below what a person would see on a 16:9 screen. (Hope that makes sense.)

wet glen
#

so will everyone see the same ?

#

i am confused ๐Ÿ˜›

tropic charm
#

No, that script basically forces the camera to match the designed width of the game.

wet glen
#

so what do i do now?

tropic charm
#

Well, if you want to play around with that script then save it as SetupCamera.cs, attach it to your camera and set the two properties. Initial Size needs to be set to the camera's designed Size property.

wet glen
#

but does this also force the height to work @tropic charm ?

tropic charm
#

You can make it force the width or the height. You can find similar scripts that will force the height.

wet glen
#

but i cant do both?

tropic charm
#

No, however, if you are going to run as a native app on Windows, Linux, or MacOS then there are command-line options to do that. I'm sure there's a way to use this feature programmatically as well but I've never done it.

#

If your game will run on the web then I don't know what you would do.

wet glen
#

i must be missing smt, i just want my content to be the same on each device?

#

but I cant do that ๐Ÿ˜ฆ

tropic charm
#

Yes, if you want your game to always use 16:9 (or whatever) then look into the player's command-line options.

#

And see if you can do the same thing programmatically, so the user doesn't have to use command-line options.

#

Look for the Unity Standalone Player command line arguments section.

wet glen
#

well but that just makes it windowded

#

how has no one else run into this problem?

tropic charm
#

You can use the -screen-width and -screen-height options to specify a 16:9 resolution like 1920x1080.

#

They likely design their games to support a range of aspect ratios and then either match the height or width, depending on the game.

#

They may also do something similar to that script but then clip any content outside of the designed-for area.

delicate loom
#

Hey hey

#

For someone who has more experience:

#

Am I doing anything wrong here?

#
_cellpos = GetComponent<Tilemap>().WorldToCell(mouseWorldPos);```
#

_cellpos.x and _cellspos.y simply return the mouseposition rather than a cell

#

what am I missing?

delicate loom
#

Fixed

#

Turns out that that is not how worldToCell works lol

robust ivy
#

mouseposition is screenposition i think, gotta use camera to turn that input to world position, then pass it to world to cell (if im right)

delicate loom
#

Yep

#

Correct.

#

I then spent 10 mins fumbling with screentoworldpoint

#

and then figured it out

broken dirge
#

Hi, Does someone here knows how to use unity's A* algorithm with an hexagonal tilemap?. I've found this video where a guy uses a square-shaped grid instead of an hexagonal one and I don't know how to change it to hexagons.
https://www.youtube.com/watch?v=HCt_CYOW9jg&ab_channel=CodingWithUnity

How to implement A* into Unity3D's Tilemap system.

Project includes graphics, and scripts

โ—Download Project: https://bit.ly/2Nz1waU
โ—Download Graphic Asset: https://bit.ly/2zpXyhf
โ—A more in-depth Astar explanation: https://bit.ly/2GLlu1A


โ™ฅ Subscribe: https://bit.ly/2FRWgOi...

โ–ถ Play video
limber thistle
#

The only difference will be that you have 6 neighbours instead of 4 when exploring new tiles

#

@broken dirge

#

I don't understand the video though. It does everything *but ** implementing the A

broken dirge
#

i think in this part of code i need add new neightbours?

limber thistle
#

Yes

#

That looks like it

broken dirge
#

thx i try do it

burnt dawn
broken dirge
#

I'm trying to use A* Algorithm with an hexagonal tilemap and Iยดm not sure about how to make the neighbours comparisons . Could anyone give me their opinion?
https://hatebin.com/kyztwdkufw

short dragon
#

can someone help me with my spring-type code i keep getting this error

#

my code^

snow willow
#

Seems like where you might want to use bouncer.GetComponent<Rigidbody2D>()

short dragon
#

that did something but now i got this

short dragon
snow comet
snow comet
#

Also for future reference send the code not screenshots

short dragon
#

ok

snow comet
#

That isn't valid since the GetComponent() method returns a value

#

But you're not storing that value in a variable

#

Also what property of that component are you trying to change

#

You need

var component = bouncer.GetComponent<RigidBody2D>();
short dragon
#

im trying to make a spring type thing

snow comet
#

Yeah I have no clue what you mean

short dragon
#

like a spring when you jump on it your character goes high like a jump

snow comet
#

Yeah I can't help you with the theory only the code errors

short dragon
#

ok thanks tho

#

same code, but i put in what you said

snow comet
#

Press Ctrl + .

#

Nevermind, there's a spelling mistake

#

It's Rigidbody2D not RigidBody2D

#

I highly encourage you to read and understand instead of copying code

short dragon
#

thanks, i will, i've just been stuck on this for a while and wanted to get it over

snow comet
#

np

mighty hare
#

what would be the best approach in creating a moveable gameobject that can only be moved by a player?

tropic inlet
#

give the player code that allows it to move the object

fathom niche
#

so i have this problem where i want to stop physics objects leaving the screen so i've put a edgcollier around it but sometimes objects still phase through, is there any way i can stop things popping through a rigidbody

robust ivy
#

is the object moving in FixedUpdate or Update

#

and are you using physic to move it

fathom niche
#

just physics

#

the wall does stop it mostly

#

but sometimes there's a lot of force and it just pops through

robust ivy
#

physic stuff run in FixedUpdate, and you usually move it with something like AddForce

fathom niche
#

so the'res no clever way of doing it, just no force vectors offsceen?

robust ivy
#

the clever way is doing it right from the start ๐Ÿ˜›

#

it shouldnt pass

fathom niche
#

okay so i could use good practicce

#

or i could get out of bounds objects to just teleport back in

#

tysm for help though

robust ivy
#

just get screen size and object position

tropic stream
#

I have a problem that my character cant move...can anybody help me?

tropic stream
#

i wrote a code in Atom but i cant move the player

vagrant nexus
#

you spelled it wrong

#

Well, capitalized it wrong

tropic stream
#

oh thank you so much

pallid kayak
#

How would i go about destroying a gameobject that has left my screen (actually a little bit further than my screen, OnBecameInvisible() wouldn't work for me)?

craggy kite
#

You can destroy it anytime, or do you want to destroy it when its out of view? @pallid kayak

pallid kayak
#

yes, when it is out of view

craggy kite
#

Then you have to have som ekind of renderer on it to make the onbecameinvisible work.

pallid kayak
#

i have made a second camera attached to the first one, can i use onbecameinvisible now?

#

the second camera's ortographic size is larger

#

i believe this should work

craggy kite
#

Okay, 2 things to concider, if you test in playmode, your scene view acts as a camera too! So you have to hide it to actually only work with your camera. And if you have two cameras, be sure none of both sees your object.

pallid kayak
#

my second (larger) camera is attached to the first one

#

how do i select which camera to use? my game view seems to prefer the camera i just added

vagrant nexus
#

change your camera depth

#

they write to the screen in order of depth

#

so higher numbers will be on top

pallid kayak
#

got it, thanks

craggy kite
#

Is your invisible thing now working?

#

@pallid kayak

pallid kayak
#

it does not

#

the asteroid does not disappear

#

made a capitalisation itsake

#

trying again

#

it works now

craggy kite
#

well, okay ๐Ÿ˜„

hot briar
#

In unity 2d, how do I make a player's sorting position update based on their position? I have tried everything I could find (Which wasn't much) and I just cannot get it to work. The main problem is that all the solutions that i did find, are for people using sprites whereas i'm using tilemaps. I just want a simple system in which the player can walk up to a wall and be in front of it a bit, and the same thing behind the wall.. Anyone got any ideas?

#

(it's for a 2.5d topdown game, think pokemon or enter the gungeon)

tropic charm
#

See step #2 of this tutorial. In fact, if you are creating a top-down style game I highly recommend you read the entire tutorial.

#
Unity Learn

Now that youโ€™ve created the base of a world for the character to move around, you can add some GameObjects to decorate. In this tutorial, you will: Decorate the world youโ€™ve created Customize the way that Unity renders your Sprites Reuse GameObjects using Prefabs Want to learn more about 2D Game Development with Unity? Connect with an expert Un...

hot briar
#

oh i hadnt found that one yet, ill read it! thanks!

#

hope itll fix my issues

tropic charm
#

It is a really good tutorial. Good luck with your game.

hot briar
#

okay sadly the tutorial did not really show me anything. i had already tried all of these things.. @tropic charm

#

mostly as this is again about seperate sprites and not tilemaps

#

Like is my only option to just build the level with seperate sprites besides the floor for which I can use a tilemap

tropic charm
#

Ah gotcha! I misread your original post.

#

I've messed around with what you are trying to accomplish and, yes, it is tricky. I think most people split the tilemap into two layers. One that the player is always in front of and another that they are always behind. The designers don't let the player walk anywhere that would be problematic so far as the draw order goes.

hot briar
#

hmnm

tropic charm
#

Use sprites if you want proper draw order, I suppose. Tilemaps for everything else. It might even be better to draw the map in something like photoshop to get better division between the layers.

#

You could split tiles between layers that way.

hot briar
#

but alright i got it working like you said yea

#

just make the colliders a bit bigger to prevent the player from goin there

#

it works like this

#

thanks!

tropic stream
austere iron
#

Is it a sprite or a ui object?

austere iron
tropic stream
#

i think its sprite

scenic patio
#

How can i spawn platforms infinetly around the player in both axis?

#

but i dont want them to collide or be too close

violet flame
#

any resources for creating skeletal animations or sprite sheets using vector art?

#

plenty of resources for doing either technique with pngs, and importing vector art via SVG Importer seems simple enough

distant pecan
austere iron
keen solar
#

Hi guys. I have another issue.
i have created a empty object
i have a button
i have the code/script written correctly to get the game to (Application.Quit();)
its connected, and the function is selected in the dropdown menu
however, nothing happens when the game runs.
the debug.log dosent show either. any help would be greatly appreciated

snow willow
keen solar
snow willow
#

Yep that all looks correct

#

Now there's only one issue though

keen solar
#

?

#

i dont even get the debuglog

snow willow
#

Yeah that's teh part that's confusing me

#

that part should work

#

but Application.Quit() doesn't work in the editor

#

here's my quit game code for reference of what you need to do:

#
        public void QuitToDesktop() {
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
        }```
keen solar
#

ok...

snow willow
#

But yeah the debug.Log should still be running I think

keen solar
#

but aside the fluf. i just want a hard quit/exit

snow willow
#

even if the Application.Quit doesn't work

keen solar
#

nothing pops up

snow willow
#

No I get that - Application.Quit(); doesn't do anything in the Editor is what I'm saying

keen solar
#

sorry.. little stressed with the simple codes not working

snow willow
#

If you put the Debug.Log before the Application.Quit(), does it print then?

keen solar
#

i can get the coins and pain images to spawn but this dosent work

craggy kite
#

Whats the error?

keen solar
#

no

#

it dosent change, before or after

#

i do know that most things are to be put before the exiting code to make sure it hits it, but this case, it dosent respond one way or the other

#

and its crazy, i can get this image/scene to show for a game over, so its loading but not exiting

#

i have the same issue with the restart button

snow willow
#

One thing that may be hurting

keen solar
snow willow
#

I see you have some warnings about missing scripts etc..

#

that may be causing an issue

#

you should go clean that up

keen solar
#

this is like, legit my first game.

snow willow
#

Okso if nothing is working at all there may be an issue with the raycast hitting your button

keen solar
#

? i reset everything to 0..

snow willow
#

If you look in scene view, are there any other UI elements that may be overlapping with that button?

keen solar
#

no..

snow willow
#

Another way to debug. Find your EventSystem object in the hierarchy

#

and click on it

#

so that you see its inspector on the right side of your screen

#

then at the bottom, you should see a window like this:

#

Then while you are playing your game, your EventSystem will update that window with various information about what UI object you are hovering over and clicking on

#

when you try to click on your button, see what object shows up there

#

If it's something other than your button, then something is blocking the button

keen solar
#

ok
should i outright add it , i dont see it added to any of the objects

snow willow
#

(btw do you get the various animations for your button as you mouseover and click on it)

#

If you don't have an event system at all

#

that's your problem anyway ๐Ÿ˜„

keen solar
#

omg..

#

ok, so no, i dont see any event system

snow willow
#

You should also double check your canvas object

#

and make sure it has a graphic raycaster

keen solar
#

it has transform and the script

#

would this change for 2d?

snow willow
#

It's a canvas

#

they're the same

keen solar
#

ok

snow willow
#

2D/3D doesn't matter

severe cobalt
#

I got an issue. I have a damaged animation and I am trying to get it to play for one second in my code before it turns off the trigger. What is a good way to set a one second countdown for a trigger in c#

snow willow
#

So double check that you have this:

  • An EventSystem anywhere in the scene
  • An InputModule on the EventSystem object
  • A GraphicRaycaster on your Canvas object
snow willow
#

The C# code should just set the trigger

#

and the animator will handle the rest

#

assuming you set up your state machine properly

keen solar
severe cobalt
#

I need to have it turn off the trigger after use and the animation play. Should there be a way to do that in the transitions?

snow willow
#

i.e. when the transition reads the trigger, the trigger will be unset automatically

#

that's the difference between a trigger and a bool

severe cobalt
#

Ok, I will play with that. I got a lot done today pretty happy.

#

Thanks

terse thorn
#

i have this error, the code here is the code anchored to the enemy ships that instantiate every 5 seconds, the code is suposed to rotate the ship to the position of the player, but aparently they just aim the player in first frame and no more

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

public class EnemyAiming : MonoBehaviour
{

  public Rigidbody2D rb;

  private GameObject player;
  private Transform playerT;
  private Vector2 target;

    void Start()
    {
      player = GameObject.FindGameObjectWithTag("Player");
      playerT = player.GetComponent<Transform>();
      target = playerT.position;
    }

    void FixedUpdate()
    {
      Vector2 lookDir = target - rb.position;

      float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg -90;
      rb.rotation = angle;
    }
}```
snow willow
#

You're just saving it in that Vector2 variable target

terse thorn
#

i understand, what should i do to fix it?

snow willow
#

You would have to change the code in the FixedUpdate to this:

Vector2 lookDir = playerT.position - rb.position;```
#

get rid of the target variable entirely

terse thorn
#

ok

#

let me test it

#

error

snow willow
#

cast it to a Vector2

#

Vector2 lookDir = (Vector2)playerT.position - rb.position;

terse thorn
#

ok

#

thanks it works

snow willow
#

๐Ÿ‘

terse thorn
#

have a good day

#

or night

#

or whatever

#

oh

#

i almost forget

#

i have another problem

#

this is with the enemy spawning

#

i have this error, im making a clock that registers the time (left down corner) and i want it that each 60 seconds the time between each instantiated enemy is reduced by one second, but idk why does not work ยฏ_(ใƒ„)_/ยฏ

snow willow
# terse thorn

When you want to compare for equality you have to use ==

#

= is the assignment operator

#

it sets the thing on the left to the thing on the right

#

that's why the error is sayting "the left hand side of an assignment must be something..."

#

it things you're trying to do an assignment

#

regardless - instead of writing wave1 == true

#

you should just write wave1

terse thorn
#

ohhh

#

let me try changing it to ==

snow willow
#

wave1 is already a bool

#

so by writing wave1 == true it's like writing true == true or false == true

#

you don't need the second == true part at all

snow willow
#

e.g. if (Wave >= 60 && wave1) is perfectly valid

#

it may be fine as a beginner to leave the == true if it helps you though

terse thorn
#

ok, error fixed, man, you are so good, you are even explaining me how the code i used works ๐Ÿ˜‚

severe cobalt
#

I switched from bool to trigger. How do I get the animation to play for one second when it triggers? I am in the animator.

snow willow
#

and the speed you have for the animator state

severe cobalt
#

So do I make it so itโ€™s not interrupted and then make the clip one second worth of sprites?

snow willow
#

so in your animation clip

severe cobalt
#

Long story short trying to trigger a damage animation to play for one second to let the player know they were hurt. I want to pair it with a minor knock back to move them away from the enemy.

snow willow
#

you should have it run from 0:00 to 1:00

#

let's start with the clip. Is the clip 1 second long?

severe cobalt
#

I will play with that now. Thanks! I am am new and done pretty well so far. Thank you!

snow willow
#

once you have the animation clip as 1 second long, we will move to the next part

#

you should be able to preview it in the Animation window and it should play for 1 second.

severe cobalt
#

Thanks. I think I have a knock back from beachys I will watch. Try to do it on my own first.

snow willow
#

sure

severe cobalt
#

Been using him, unity learn, and GitHub

keen solar
#

@snow willow i wound up deleting the entire scene, but i have a new question

#

i was following a youtube link, i wanted to know if it was still valid

#

is it ok if i post it here?

snow willow
#

np

keen solar
#

๐ŸŽ Support me and DOWNLOAD Unity project: https://www.patreon.com/posts/46483799?s=yt

This tutorial/guide will show you how to create a simple game over screen for you game that will allow players to restart the level or even go back to the main menu

๐Ÿ’œ Join our Discord: https://discord.gg/hNnZRnqf4s
๐Ÿ”ต Follow me on Twitter: https://twitter.com/b...

โ–ถ Play video
snow willow
#

I mean that tutorial is from December

#

there's no way anything in it is not valid

keen solar
#

sigh

#

yet theres nothing in the vid about an event handler

snow willow
#

I never said it was a good tutorial

#

Unity should be creating an EventSystem automatically (you're talking about EventSystem, right) for you when you create any UI object

snow willow
#

If you look at that video at 1:10, you can clearly see there is an EventSystem in his hierarchy

keen solar
#

so its something that he creates

#

ok i'll go over it again..

snow willow
#

I think Unity probably created it for him automatically

#

it usually gets created when you create any UI object from the menus

keen solar
#

so

#

when creating this scene

#

he creates it within the main scene of the game

#

when i did that, the game over screen overtook/covered up the game screen

#

dose it matter if you create a seprate scene or a subscene?

keen solar
#

Sorry for being too technical

heavy fog
#

Hi everyone! I am creating a project that is a 2D dodging game. I am having some trouble with the pause button and the pause button code. if anyone could help, it would be greatly appreciated!

#

I tried a couple of things with my code

#

Sorry about the messiness

tropic charm
#

Try this script...

#
// PauseGame.cs

using UnityEngine;

public class PauseGame : MonoBehaviour
{
    private bool _isPaused = false;

    public void TogglePauseGame()
    {
        if (_isPaused)
        {   // Currently paused.  Resume game...
            Debug.Log("Resuming game...");
            Time.timeScale = 1;
        }
        else
        {   // Currently running.  Pause game...
            Debug.Log("Pausing game...");
            Time.timeScale = 0;
        }

        _isPaused = !_isPaused;
    }
}
#

Attach that to your button and setup the onClick similar to this...

#

If you don't see those debug messages then you've done something wrong.

frank vector
#

HI! I currently working on a combat system for a 2D top-down game. For Hit detection I wanted to use colliders as hitboxes, but the game would allow for different types of weapons, each type with a different hitbox. The most simple approach would be to just create gameObjects with the various hitboxes but I was wondering if anyone could give me some pointers for a more flexible system that allows me to adjust the hitbox pretty much however I choose.

craggy kite
#

Hm, not sure if its worth it but you can use the meshrenderer bounds to get max and min values of your mesh and therefore swap out the collider size @frank vector

frank vector
#

That would however only allow changing the collider size. Still would have to create collider shapes for each type (line, arc, circle etc.). I was thinking about maybe creating polygon colliders at runtime (basically onbutton"attack" -> check weapon -> create collider), but I'm worried that may impact performance.

uneven shuttle
#

Do you need pixel perfect hit detection? if not, you could just create an approximate collider box in the general attack direction

frank vector
#

No don't necessarily need pixel perfect hit detection. I think I will play around with the collider creating idea and see how much it impacts performance based on number of enemies. Thanks!

uneven shuttle
frank vector
#

Oh I actually did not know about OverlapBox. I think that may be very useful! Awesome, thank you!

knotty barn
#

What sort of hitboxes are you trying to create? Often several physics queries are made from previous weapon position to current weapon position to model the attack as it happens

#

When trying to model reasonably very accurate hit collision

frank vector
#

Of the top of may head: A straight line hitbox (spear), an 45ยฐ arc hitbox (swinging axe), a circle (hammer) and maybe a rotating arc collider (spinning attack).

knotty barn
frank vector
#

Thank you, I will take a look at it

tropic stream
#

the life text is in the game scene in the right corner, but when i build the game the text is not in the right corner...?

snow willow
craggy kite
#

what are your recttransform inspector settings ?

tropic stream
#

the cam settings? or what

craggy kite
#

On your screenshot

#

the Rect Transform, open it up, show it to us

snow willow
#

Cam??? No the anchors on the rect transform

craggy kite
#

I guess your resolution on the game view is not the same as your build running device, so your UI is not scaling properly, maybe because of what @snow willow said about anchors or your whole Canvas is set to a specific Resolution or not scaling.

tropic stream
craggy kite
#

This is setting your object to a specific offset from the center, so if your resolution gets higher, the offset will not be on top right.

tropic stream
#

okay... so what i need to enter in there?

craggy kite
#

I recommend watching a little tutorial on youtube about rect transform and anchors, so you undersatnd, what its doing ๐Ÿ™‚

tropic stream
#

i dont want create a big game its just for a school project

craggy kite
#

You want your anchors to be all 1 and your posx and y be 0 or whatever fits your visuals

severe cobalt
#

Coding question. I need to check if "amount" is negative and "IsInvincible" is false before setting a trigger. I can't seem to get the if statement right. What should the if statement be?

craggy kite
#

It just asks for the amount to check for invincible, after that it will always play the IsHurt triggered animation

severe cobalt
#

Well the issue is it's playing when I get a health pickup

#

I wanted to add a nested if statement of "If Invincible or amount is above 1"

craggy kite
#

Yeah, you are never asking before setting the trigger it the amount is below 0

#

you are getting into the if statement, ask < 0, then exit it and just play the trigger

#

You should put that trigger into your if statement at the end of it

severe cobalt
#

I was thinking
If (isinvincible && amount >0)
{
Play animation
}

#

but not sure the exact code I can't seem to get it right

craggy kite
#

if your amount is < 0 && !isInvincible, than play hurt animation, else if amount > 0 play health animation

severe cobalt
craggy kite
#

this was just written out, no code... remove the "is"...

severe cobalt
#

I did, still having a slight issue. I think I get the basic I will play with it. Thank you

craggy kite
#

Yw

severe cobalt
#

Now I just need to figure out my animation tree it's having issues switching to damage while falling

craggy kite
peak stirrup
uneven shuttle
#

So i have a map generator that creates a map. Now I want to put tiles on the map, hopefully using rule tiles or something similar. I got it working (see screenshot), but in order for that to work I had to manually create 64 different rules (16 for floors, 48 for walls due to corners) with 64 different tile variations. Also, i now have basically upscaled the resolution of the map because each 1 unit for the map is 32 px, while the actual tileset and character resolution should be 16 px - i can scale the characters up as well, but that probably will look shady. Is there a better way to actually accomplish this while keeping the overall resolution intact?

ripe edge
#

hey guys dose any one have an idea about how to manage to move the scroll rect that contain the inventorys items on it up and down when u select an item in the inventory??

#

without moving it with the mouse

#

thank you ! โค๏ธ

tropic charm
#

If you can figure out the correct value then you can use the verticalNormalizedPosition property.

split lava
#

@peak stirrup do you have a tilemap collider on your tilemap and some collider on your player?

split lava
#

@uneven shuttle are u asking two questions in ur message

#

for the scale, you can scale your entire tilemap just using its transform, but there are also scale options in the tilemap component

#

(or the grid component, dont remember)

peak stirrup
#

@split lava yes, I have a tilemap colider on my Tilemap and a box colider 2D and a circle colider 2D on my player

split lava
#

can you explain what happens when the player clips into the wall more in detail

peak stirrup
#

If I land on the floor from high up or hit a wall or ramp moving fast it goes inside

split lava
#

oh thats a pretty simple fix

#

just go to your player's rigidbody and change collision detection mode from discrete to continuous

peak stirrup
#

ok

#

Thanks so much! My game no longer feels scuffed to play

split lava
#

lol no problem

radiant lake
#

can anyone help me with a sprite problem ?
i have a list of total sprites in the game.
then i randomly pick a few of them , putting them into a fixed array.
i'm trying to grab each one of these sprites and put them into a spriteRenderer to display all of them at the same time, but all i'm getting is the final sprite that is in the array. and also it's accessing the spriteRenderer of the GameControl in the hierarchy not the ones from the sprites that are in the array

inland osprey
#

okay this is my code, works fine but it dashes on arrow keys, how to i change that to for example
so z + w forward dash instand of arrow key etc. https://hatebin.com/klqcjgwhnn

severe cobalt
#

Trying to get my char to stick to the platform. It moves without them and I have not been able to get them to stick. I am using some code I found on a site for suggesting platforms and tried to alter it a little.

#

I added RigidBody2D to the platform and changed it to update contentious but reading how to I can't figure out how to set the char to add the platform's velocity.

#

Woot! Got it working! Found it on Unity Forms

uneven shuttle
#

So i've got a field of view working, essentially just by shading the tiles with a different color. Just wondering, would there be a way to smooth the edges to not make it look as tile-y?

ripe edge
pastel hatch
#

I'm trying to make a sprite jump, but whenever I add ForceMode2D.Impulse it doesn't move whenever I call the function compared to if I just leave it out
I've looked online to see what the issues are but changing the rb to dynamic doesn't fix it
Does anyone know where I'm going wrong with this?

desert cargo
#

So they normalised distance from the top of the plane and the top of the visible area

#

If that helps

pastel hatch
#

Just realised I posted in the wrong area again blegh xD

green veldt
#

question:

#

how would i make "wires"

#

you can drag the ends to manipulate the shape

#

my current guess is to have two gameobjects, then a line renderer that draws between them...?

green veldt
#

can i get a box collider object from collider?

#

or collision2d

vagrant nexus
#

properties like bounds are in the base collider class, and would be accurate without casting to the derived version

green veldt
#

I tried seeing if I could get some properties but it didnt work

#

Specifically I need the center

vagrant nexus
#

isn't there bounds.center?

green veldt
#

Ooh I think ur right loll

tropic stream
#

why is there a big X?

#

normally there would be text

proper flame
#

Doesn't that mean it's flipped, so facing away from the camera?

#

The height/width is probably a negative value

#

@tropic stream

tropic stream
#

im looking

#

weird it was flipped..

#

@fallow tendon Do you know why my text isn't where it should be, when i build the game?

craggy silo
#

@tropic stream when you do UI it's better do use game view instead of scene view

#

then you can know if it's actually fliped because game view UI doesnt move

#

and in scene view you can by accident go 'behind' your UI

#

try game view and tell me if it's flipped there too ?

tropic stream
#

i fixed it already

#

i think

fallow tendon
#

big guess from me but maybe the screen size/resolution on build is different from testing and it's getting pushed around based on that

tropic stream
#

i made now a new resolution (1920x1080)

ripe edge
#

and here is the result !

gaunt tulip
#

im sort of confused with this code could someone help

#
    private Transform playerPos;

    void Awake()
    {
        playerPos = GameObject.FindGameObjectWithTag("Player").transform;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = new Vector3(playerPos.position.x, playerPos.position.y, transform.position.z);
        transform.position = new Vector3(Mathf.Clamp(transform.position.x, -3.4f, 3.4f), Mathf.Clamp(transform.position.y, -2.86f, 2.86f), transform.position.z);
exotic topaz
#

i want a code for 2D for movement (jumping , moving) . I m not a very good coder and i want a code to put in my game .

tropic inlet
#

@gaunt tulip Help with what?

torpid spruce
#

So i am trying to make a answer box, and when the answer is correct i want something to flash green, and when its wrong i want something to flash red.

I have the code working on an if else, and it works right now with saying "correct", "incorrect"

I was thinking of using a coroutine that set a panel to active, wait, then set active to false, and use a float value to control how quickly this panel turns on and off, so it will look like it is flashing after the answer is correct

PROBLEM: When i open the menu before answering anything the panel turns on, waits, turns off then thats it, it does not happen every time the IF statement tells it to

Is there any thing in coroutines that i need to return to have it happen again? Or can you not put it in a If/else statement?

torpid spruce
#

or is there anyway to get a WaitForSeconds, outside of a coroutine

snow willow
#

if you wwant something to repeat in a coroutine, you would use a loop

#
IEnumerator DoSomething(int numberOfTimes)
  for (int i = 0; i < numberOfTimes; i++) {
    // do something
    yield return new WaitForSeconds(1);
  }
}```
torpid spruce
#

so it doesnt work in a if else then? meaning i can not execute it each time i need it to?

snow willow
#

I'm not really sure what you mean by that

#

if/else statements work inside coroutines like anywhere else

#

Maybe share your code?

torpid spruce
#

i tried pasting it just now and it disappeared

#

let me try again

snow willow
#

paste there - hit the save button and share the link

torpid spruce
#

ty

snow willow
#

ok so...

#

on line 27 right now

#

you're just calling waiter()

#

which isn't how coroutines work - that won't actually make any code inside waiter() run

#

you need to use StartCoroutine(waiter());

torpid spruce
#

i see, im sorry im good with unity, bad with hard coding, let me try calling it like that

#

@snow willow you are my hero, if there is anything i can help you with please let me know

desert cargo
desert cargo
gaunt tulip
#

@tropic inlet what the code actually does

terse thorn
#

hello, it's me again!, i need help with a problem, the problem is the next;

https://hatebin.com/heyqkvesfa (code to spawn enemies)

with this code i want to make a enemy spawn in a random location between X number and X number in coordinates, i made that with Random.Range, first i only had one place of enemy spawning, the superior part of the map, now i want the code to decide first in wich place it will spawn an enemy (between x and x coordinates of left, right or up), then decide wich enemy and then spawn it only when timeBtwEnemy is zero, the problem is that when i hit play it just instantiate the enemy00 GameObject each frame in 0 0 coordinates and dont spawn other enemies and dont respect the timeBtwEnemy and idk why this happen so if someone can help me or at least told me what is wrong here

(when i say x and x on the explanation im just refering to "a number" not the int called "x")

tropic charm
terse thorn
#

uh?

tropic charm
#

The && operator has higher precedence than the || operator so when you say if(x == 0 || x == 1 && y == 0) you are really saying if(x == 0 || (x == 1 && y == 0))

terse thorn
#

ohhh

#

let me try something

terse thorn
#

the problem persists

#

if(y == 0 && (x == 0 || x == 1)) i basically just changed to this

tropic charm
#

That look correct. I assume you changed all of the other if statements. You might post the latest revision.

tropic charm
#

Are you sure that link is for you latest changes?

terse thorn
#

uhh, let me see

#

haha, no, my mistake

terse thorn
#

did you found a way to fix it? ๐Ÿง

#

screenshot of what is happening

#

another screenshot of the editor

tropic charm
#

I do see another problem. The big chain of if/else if statements that follow the if (timeBtwEnemy <= 0 && alive) statement look like they should be placed in that block instead of outside of it.

#

If that makes sense. I'll post the changes here in a second.

terse thorn
#

no, i think that should break the stuff

#

if i change first if of the else if chain to an else if it will not execute when is called

tropic charm
#

I reformatted your code so I could make more sense of it.

terse thorn
#

wait, you can put an if inside another if!?

tropic charm
#

You only want to spawn a new enemy when (timeBtwEnemy <= 0 && alive) so the code to do that should be in that block.

alpine frigate
#

Hi everyone, does anyone know why I am not getting an "in between value" when im using my controller?```css
private void handleMovement()
{
if (!isUsingController)
{
direction = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
}

    else
    {
        direction = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        print(direction);
    }

    direction.Normalize();

    rb.AddForce(direction * speed, ForceMode2D.Impulse);

    //Debug.DrawRay(rb.position, new Vector3(direction.x, direction.y, 0f) * 500f);

}```well.. im getting "the in between" when I print it but when I apply the force its either all or nothing
tropic charm
#

Yeah, it gets really messy so at some point you might think about breaking things into different functions. I would get it working before doing that, however.

snow willow
terse thorn
#

MAN

#

it works

#

thank you so much

#

i did'nt think the problem was so stupid

#

LMAO

#

goodbye

tropic charm
#

Cool. Have fun!

snow willow
terse thorn
#

now i know you can put an if iside another if

#

that will make things a lot easier

#

tysm

snow willow
#

Why do I feel like he's going to use that knowledge for evil and not good?

tropic charm
#

And watch out when mixing && and || in an if statement. Most people always use parenthesis so that it is explicit how the compiler will evaluate the statement.

terse thorn
#

ok

alpine frigate
#

@snow willow ohh I see.. Im normalizing this vector because I dont want my player to go faster in some directions. If I remove that line, my controller will work fine but my player will go faster in diagonal.. Is their a way I can make my controller return "inBetween values" while not being able to go faster in corners?

alpine frigate
#

ohhh nice I think this is exactly what I was looking for ๐Ÿ™‚ thanks man

snow willow
#

np

#

That's the old GoldenEye 007 problem ๐Ÿ™‚

#

used to run around diagonally all over the place

alpine frigate
#

lmao yeah

#

playerCam.orthographicSize = Mathf.Lerp(6f, 9f, 3f);

#

any idea on why its poping to 9 instead of lerping?

tropic charm
#

I think the 3rd parameter should have a value between 0 and 1.

#

You need to call Lerp in steps using Update() or something similar and vary the t parameter from 0 to 1.

#

If that makes any sense. There are also 3rd party assets that will do that for you such as DOTween.

alpine frigate
#

hmm I see

#

thanks mate

tropic charm
#

Sure.

mortal nexus
#

Im having this stupid bug, when i walk I have random yellow lines show up? Anyone know what is going wrong??

keen solar
#

hello i have another issue with my unity game

#

i just deleted a completly diffrent scene, and suddenly my player sprite dissapears when the game "plays" in the editor

#

now im getting a werid issue about im trying to access a transform object thats deleted

#

i checked my code and objects and everything is stil connected

tropic charm
mortal nexus
#

okay

#

thx

mortal nexus
#

*checked

tropic charm
#

Are you using a TileMap or did you place the tiles manually?

mortal nexus
#

TileMap I think

tropic charm
#

So you have a Grid and Tilemap in you scene?

mortal nexus
tropic charm
#

Hmm. Are you using a Cinemachine camera or the standard camera?

mortal nexus
#

Im pretty sure im using the standard camera, but im not sure

keen solar
#

um..

tropic charm
#

If you didn't change it then, yes, you are likely using the standard camera. The Cinemachine camera is improved and I'm pretty sure the issue you are seeing has been fixed with it.

mortal nexus
#

okay

tropic charm
#

There might be ways to work around the issue with the old camera.

mortal nexus
#

okay

tropic charm
#

The Cinemachine camera is really nice. Once you get further along in your game it will provide a lot of feature that you would have to otherwise implement yourself.

mortal nexus
#

ok thanks ๐Ÿ˜„

keen solar
#

hey @tropic charm when you are done may i ask a few questions?

tropic charm
#

I saw your question @keen solar but I don't really have any suggestions. You might post screenshots of the errors.

keen solar
snow willow
tropic charm
#

@keen solar If you click on the Console tab and find that error and double-click it it should pull-up the file where the error occurred.

keen solar
#

when i click on it, everything points to the player sprite

#

however when teh game plays the sprite dissapears

snow willow
tropic charm
#

Yeah, tracking that down might be tricky. You should double-check all of the code that deals with the player object.

keen solar
#

i dont actully.
this only started happening after i deleted a sub scene that displayed a sign of game over

#

even when i add a new empty object, it dissapears

tropic charm
#

Is the sprite being removed or greyed out in the scene view when you run the game?

mortal nexus
mortal nexus
#

.. it also shows up on the scene viewer

tropic charm
#

@mortal nexus Really? Are the sprites the proper size? Does the Pixel Per Unit setting match?

mortal nexus
#

yep

tropic charm
#

Double-check your grid settings.

mortal nexus
#

okay

#

is that correct? it looks the same to yours

tropic charm
#

Yep. That looks okay.

mortal nexus
#

what do you think the problem is then?

tropic charm
#

I don't know. It sounds like the classic tilemap 'bleed' problem but I've never seen that when things are setup like you done.

#

What do your Background TileMap settings look like.

mortal nexus
#

I think this is it

tropic charm
#

The scaling kind of worries me.

mortal nexus
#

what should I change it to?

tropic charm
#

Here are the settings from a project I'm looking at.

#

I'll play around with the x and y scale and see if I can reproduce what you're seeing.

mortal nexus
#

okay

#

thanks

#

In a sec I have to go eat dinner so if I dont respond right away, that is why

keen solar
#

...

tropic charm
#

I didn't notice any problems when I messed with the scale or position. You might try setting your transform up like mine and see if it helps.

mortal nexus
#

Okay

tropic charm
#

@keen solar From the sound of it you might have somehow got the IDE confused.

keen solar
#

ide? like the programming tool im using to code the script?

#

visual basic?

tropic charm
#

The Unity editor.

keen solar
#

ok.
how do i fix it?

tropic charm
#

Have your restarted Unity? I would start there.

keen solar
#

restarted

#

still the vanishing player

#

created new empty sprite, re added all rigid bodys, 2d box collider and scripts and the same thing happens

tropic charm
#

Are you attaching a script to the sprite?

keen solar
#

yes

#

its for the players movement

tropic charm
#

You might post the code from that script. It must be doing something fishy.

keen solar
tropic charm
#

This doesn't look right...

#
        if(PlayerHealth >= 0)
        {
            Destroy(gameObject);
        }

keen solar
#

adds / */ *

#

thats very weird
why would that script fire now when it wasnt before when the defunct scene was there?

tropic charm
#

I don't know. Maybe it was just a coincidence. Anyway, I think you want to use <= (less than or equal) instead of >= (greater than or equal.)

keen solar
#

ill try that

#

thanks for your help

tropic charm
#

Sure.

still tendon
#

Hi. So I am making a game called adventure 2d and I have the character image but the script does not work and it it wasn't compiled properly. Can anyone help?

fair cloud
#

solved!

pastel hatch
#

@still tendon Have you got a screenshot of the script?

remote moth
#

can i use two box colliders and can I query which one was touched?

dim bloom
#

I am making a 2d game and I want the player to rotate instead of moving, so that it can only move forward or backward. How do I make it so it would rotate?

tropic inlet
#

@dim bloom

dim bloom
#

thanks

loud steppe
#

i am making 2d game in unity ,i have problem .problem is i want to when damaged from enemy ,knockback to damage direction

#

how can i do

torn meteor
#

can anyone help explain why instance wont move to the position printed?


using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using UnityEditor.UI;
using UnityEngine;

public class levelGenerator : MonoBehaviour
{
    Object[] enemies;
    // Start is called before the first frame update
    void Start()
    {
        enemies = Resources.LoadAll("enemies/");
        Debug.Log(enemies[0]);
        generate(1);
    }
    public void generate(int level)
    {
        for (int i = 0; i < 4; i++)
        {
            Random.InitState(level + i);
            GameObject enemy = enemies[0] as GameObject;
            Vector3 screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.safeArea.width, Screen.safeArea.height, Camera.main.transform.position.z));

            GameObject current = Instantiate(enemy, this.transform.parent) as GameObject;
            Vector3 pos = new Vector3(Random.Range(0, screenBounds.x), Random.Range(0, screenBounds.y), screenBounds.z);
            Debug.Log(pos);
            current.transform.localPosition = pos;
            
        }
    }
    void Update()
    {

    }
}
snow willow
#

so it will go to that position - but transformed by its parent's transform

torn meteor
#

@snow willow oops i just switched it to local position when trying everything. it didn't work with regular position either

snow willow
#

Is it not moving at all?

#

If it's not moving at all the position maybe is being controlled by a CharacterController or an Animator

dim bloom
#

I do not understand why it is not recognizing transform

snow willow
#

using UnityEngine;

#

as the error suggests

#

Oh also - it's Transform

#

not transform

#

for the type

dim bloom
#

ok

pastel hatch
#

I've got an issue with the colliders, they're taking a little while to show any effect and I'd rather they happen instantaneously
How can I fix this? :P

snow willow
#

why not use OnTriggerEnter2D?

#

oh wait

#

no you're right

#

your problem is that you're reading Input.GetMouseButtonDown() inside OnTriggerStay2D

#

OnTriggerStay2D is part of the physics update

#

so it doesn't run every frame

pastel hatch
#

Ahh, should I write it to a variable then?

snow willow
#

so sometimes you will miss input

#

yeah read that in Update

#

save it in a variable

#

check that variable instead in your OnTriggerStay

pastel hatch
#

Brill, thanks very much

torn meteor
radiant lake
#

can anyone help me with a OnMouseDown problem. ?
in my start i instantiate a few GameObject sprites with a 2D box collider on them. i'm trying to click on them and disable them, but for some reason the OnMouseDown section is not getting exacuted

tropic charm
#

Where did you attach the script with the OnMouseDown() method? From the API doc: This event is sent to all scripts of the GameObject with Collider or GUIElement. Scripts of the parent or child objects do not receive this event.

snow willow
#

Also I believe you need an EventSystem and a PhysicsRaycaster in the scene for OnMouseDown to work but not 100% confident about that

radiant lake
snow willow
# radiant lake

can you show what other components this object has? (Show its inspector)

hollow crown
tropic charm
#

Just from the name of the file it doesn't sound like that method is attached to a game object with a collider.

flat hemlock
#

how does one make bullet hell paterns

radiant lake
snow willow
# radiant lake

that can't be the same object because I don't see your script on it

tropic charm
#

I can make it work by attaching a script that has the OnMouseDown() method in it to the game object that has the collider.

#
using UnityEngine;

public class MonkeyCollider : MonoBehaviour
{
    [SerializeField] private Monkey _monkey;
    [SerializeField] private bool _isFront;

    void OnMouseDown()
    {
        Debug.Log("Mouse down!");
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (_monkey)
        {
            _monkey.Damaged(_isFront);
            Destroy(other.gameObject);
        }
    }
}
radiant lake
snow willow
radiant lake
snow willow
#

on the same object

#

you need a script on the object you're instantiating

radiant lake
#

so then i'll have to also attach the script to them also while instantiating them.
will this also work if i make them a child to the game control ?

snow willow
#

that you are instantiating

#

or whichever object you're copying

#

and no it doesn't work on parents or children as mentioned above

radiant lake
#

ahhh ok , thx

rare yarrow
#

hey i need some help with my game

tropic inlet
#

dbz profile pic

#

ur arms must be so big irl

remote moth
#

If i set a object to a child from a other, then i can't set the position

GameObject a = Instantiate(SlotPrefab) as GameObject;

a.transform.parent = this.transform;
a.transform.position = new Vector3(i, 0, 0);
remote moth
ripe edge
#

hey guys hope every one doing good โค๏ธ

#

i have a question i have to scripts in my camera one for camera follow player with boundaries and the other one is a camera shake script the problem is idk why the camera shake didnt work when the the camera follow script ๐Ÿ˜› any one have an idea ??

knotty barn
#

@ripe edge Use thirdparty code hosting sites.

hearty anvil
#

Idk if this is the right place to ask but I am having a problem with the Destroying Assets is Not Permitted error

knotty barn
#

@hearty anvil Are you calling Destroy to an asset reference?

hearty anvil
#

I imagine I am but I'm not trying to

#

This is the problematic bit of code

#

Bossenemy is a public GameObject I initiated at the top of this script

#

Btw pls bear with me if I get some terminology wrong I've recently got back into Unity after a like 6 month break and I'm still a beginner ๐Ÿ˜“

knotty barn
#

@hearty anvil Bossenemy likely isn't pointing to an instance in the scene, but the file itself

hearty anvil
#

Hmm that is what I suspected. But do you know how I would go about fixing this?

#

It feels like I'm missing some sort of basic principle because this is an error I would likely see very often otherwise given it's such a simple thing as destroying an instance

knotty barn
#

Hard to say. If you dragged prefab to that field, then it will point to that prefab until it's replaced. Generally I don't share prefab fields with instance fields and make it clear when naming the field.

#

Just need to investigate what is assigned to that field

hearty anvil
#

Replaced you say? How do you replace a prefab with an instance?

#

And if you can do that can you then replace it with a clone and destroy the clone?

knotty barn
#

As in assign something to a field

#

Bossenemy = GameObject.Find..., or Bossenemy = Instantiate...

hearty anvil
#

So shouldn't this have worked, then?

#

This is in my startup script run right at the start

knotty barn
#

I don't know how any of this connects to the Bossenemy field

hearty anvil
#

I dragged the prefabs into the GameObject tabs, was I supposed to put something else there?

#

I'm just trying to find what's causing the problem

#

Tbh this error in general just confuses me

#

The script I showed creates an instance of the Bossenemy

knotty barn
#

Again, I don't see where the Bossenemy is referenced outside of the Destroy statement

hearty anvil
#

Idk, what is it in particular is it you need to see?

tropic charm
#

Do you have a script named Bossenemy? I don't see how your code would compile otherwise.

knotty barn
#

What is assigned to Bossenemy, since that is the one pointing to an asset

hearty anvil
#

I don't have a script by that name. Bossenemy is a public GameObject variable in the bossController script which is connected to the object called BossEnemy (with the capital E)

tropic charm
#

You should post your scripts so that we can see everything in context. Use hatebin if they are longer than a few dozen lines.

hearty anvil
#

Ah okay

#

Hang on I'll post the Boss script and the bossController script

#

Sorry if I've been difficult so far, most of this is new to me ๐Ÿ˜…

tropic charm
#

No problem. My guess is that you dragged a prefab into the Bossenemy property. If so then you can't call Destroy() on a prefab. Drag the instance from the scene into that property instead.

#

Or, maybe you want to be calling Destroy(this.gameObject) if that script is attached to the enemy boss.

hearty anvil
#

Yeah I have just noticed that the prefab is losing health when it gets shot at but the instance in the game is not losing health

#

When the instance in the game is the one actually taking hits

#

It won't let me drag the clone in the scene view onto the Bossenemy property

tropic charm
#

I don't know why that would happen.

still tendon
#

what

hearty anvil
#

You mean why it wouldn't let me?

still tendon
#

am I allowed to send photos here? why did my message get deleted

tropic charm
deft niche
#

is it possible to create online strings?

still tendon
#

uhh, what i wanted to say is I have a button in my game that makes the player jump, but when I press it there's a slight delay.

tropic charm
hearty anvil
#

Gahhh I don't understand why this part of all things is so confusing. I got stuck here before. I only want this object to be instantiated and to then be destroyed when it needs to be. Idk why everything seems to be editing the prefab's properties instead of that of the instance

#

I feel like I'm doing something fundamentally wrong and I haven't noticed yet

#

I figured you drag prefabs into the GameObject fields and it does the rest

tropic charm
#

Does the boss enemy start life already instantiated in the scene? (Is it in the Scene hierarchy?) Or do yo instantiate it yourself?

hearty anvil
#

I have a GameManager object that loads up the scene and instantiates every object I need

#

Should I share the code for that script?

tropic charm
#

No, that's getting a little too complicated to wade through. Just know that, in this case, what you pass as a parameter to Destroy() has to be what was returned from Instantiate().

hearty anvil
#

Alright

#

I have this in the script at least

#

And this to instantiate them

#

I dragged the prefabs into place here

tropic charm
#

Also, if the BossController script is attached to the BossEnemy prefab then you should be able to call Destroy(this.GameObject) within that script and its base.

hearty anvil
#

Yeah I changed that but it didn't do anything

#

Note that bossController inherits from Boss and Boss is the script that has that function that destroys it

#

Not sure if that changes anything or not

tropic charm
#

From the sounds of it, if the properties are changing on the prefab during gameplay then you still have other problems.

#

No, I don't think the inheritance is an issue.

#

Your code is just mixing use of the prefab and the instance of the prefab from the sounds of it.

hearty anvil
#

Yeah that sounds about right

#

I didn't even know this was a thing though

#

Geez that means I have to figure out where I referenced the prefab instead of its instance

#

Sounds like a lot of work ๐Ÿ˜“

knotty barn
#

If the object isn't in the scene, it likely isn't referencing anything but prefabs

#

Objects already in the scene can reference scene objects

hearty anvil
#

I did instantiate the object though

knotty barn
#

That doesn't affect those references apart from the stuff you assigned while instantiating

tropic charm
#

The typical use case is that you use the prefab only to create instances via Instantiate<>() but otherwise only use the instances in the gameplay code.

#

Also, realize that you can use a prefab to create several instances--it isn't a one-to-one relationship.

hearty anvil
#

So what does this mean currently? Would it be an easy enough fix to change all references to instances rather than the prefab or would I have to start some things over?

tropic charm
#

Personally, I would start by renaming properties that expect prefabs to have 'Prefab' in the name. It looks like you are using 'inst' for instances so that's good.

#

Then I'd find all the reference and switch to using the instance.

hearty anvil
#

So if I do this for every script I should be fine?

tropic charm
#

Hard to say but that is where I'd start. You might go line-by-line so that you catch any compiler errors early. And fix them before moving on.

hearty anvil
#

Alright, sounds good

tropic charm
#

Just don't forget to leave the use of the Prefab in the call to Instantiate(). I'm betting all the other uses can be changed to use the instance.

hearty anvil
#

I guess I don't know precisely how to reference an instance of another object in here instead as a GameObject

tropic charm
#

Yeah, that's something you won't know at design time since you are creating everything dynamically. That property shouldn't be assigned in the inspector but at runtime.

#

You might have to use something like FindObjectOfType().

#

Ideally, you would have the object that is creating the instances pass this information to everyone that needs it.

#

GameObject.FindWithTag() will work too if you assign a tag to the game object in question.

hearty anvil
#

I'm getting a Object Reference Not Set to Instance of Object error now

#

I changed bossEnemy to instBossEnemy and added this line of code

#

The highlighted line here in the inherited script is raising the aforementioned error

tropic charm
#

Is the class in the second screenshot derived from the first? Maybe you need to call base.Start()?

hearty anvil
#

Yeah it is

#

That's calling an error

tropic charm
#

You might put Debug.Log() calls in those Start() methods to 1) see which order they are called in, and, 2) see if instBossEnemy is actually getting assigned a non-null value.

hearty anvil
#

Yeah the 2nd screenshot was being called first

tropic charm
#

That link shows a couple of way to call base.Start().

hearty anvil
#

Alright! It's responding as it should be now, but it isn't being destroyed when its health goes down to 0

#

And the prefab is not responding, as it should be

tropic charm
#

Woohoo! Almost there.

hearty anvil
#

Alright so how should I destroy the object?

#

Just go with GameObject.Destroy(instBossEnemy)?

tropic charm
#

Yes, if you have the instance handy then that should work.

hearty anvil
#

Ah I see my mistake, I had to move instBossEnemy in another place as well

#

Okay so when it dies it's respawning in the middle constantly, but I know what's causing that

tropic charm
#

...fix one thing and something else pops up. That's the nature of software development.

hearty anvil
#

Alright I've got it!

#

I now have a tracker for if the boss has or has not been beaten yet which decides whether one should spawn or not

#

Everything works! :D

tropic charm
#

Awesome!

hearty anvil
#

Thanks so much guys, this really helped!

#

Still, I'm surprised this error isn't more common. I got this following the orders of some instructions from an old uni tutorial ๐Ÿ˜…

tropic charm
#

Well, you'll know better now if you ever come across the same thing. Good luck with your game development journey.

hearty anvil
#

You too on your own journey SukunaYay

terse cloak
#

if I want to make a list with LayerMask, of layers that an object can collide with

#

how do I write an if statement for that?

#

what I'm trying to write is, if an object's layer is part of the LayerMask list, then the collision occurs

#

I have tried having this variable, which gives me a list in the Inspector

and later:

private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.layer == WhatCanCollide)

but this isn't working

tropic charm
#

@terse cloak I don't see any good examples in Unity's documentation that would show how to do this but LayerMask.Value returns a 32-bit value that has all of the layers bitwise-ORed together.

#

So in your case you should be able to say something like this:

#

if (other.gameObject.layer.value & WhatCanCollide.value) { ... }

terse cloak
#

I'll give it a try thanks

tropic charm
#

Looks like you'll want to say this so the compiler doesn't complain: if ((other.gameObject.layer.value & WhatCanCollide.value) != 0) { ... }

fair cave
#

So I have a small little problem, whenever I use MovePosition in my code, the gravity affect on the entity becomes significantly lower and velocity value is constantly 0.

#

My question is, why do both of these things happen?

native thistle
#

Question: I have an object with a collider and a Vector2 that stores the direction the object is facing (which can change at runtime). When a bullet collides with the object I want to check what angle the collision happened relative to the Vector2 facing, so that I can determine whether the bullet hit the object in the front half or the back half of the object. Vector2.Angle seemed like a good idea but it's giving me weird results I don't understand -- how can I do this?

tropic charm
#

@native thistle Have you tried Vector2.SignedAngle()? Vector2.Angle() will always give a positive result <= 180 degrees.

native thistle
tropic charm
#

Is the bullet rotating? Also, I don't think you should need to subtract the object position from the bullet position. The second parameter should probably just be bullet.transform.position.

#
        float angle = Vector3.Angle(_facingVector, projectileVector);

        Debug.Log("this._facingVector = " + _facingVector + " projectileVector = " + projectileVector +
                  " angle = " + angle);

#

That code there will return a value of 0 when the target is hit in the back and a value of 180 when hit in the front.

#

The projectile rotates so I had to save off its initial direction and use that as projectileVector.

twin topaz
#

Hi i am wondering what code do i require if i want to zoom the camera out on collision with a object.

tropic charm
#

Is your camera using orthographic projection?

twin topaz
#

yes

#

but @tropic charm i don't know how to zoom camera out on collision with a object

tropic charm
#

Basically, you will just have to animate the camera's Size property.

twin topaz
#

how do i do that, i am a novice at coding lol

tropic charm
#

Easiest way to do it would be to create an animation on your camera. Select your camera in the Scene Hierarchy, open the animation window and click 'Create'.

#

...add orthographic size as a property then change the values in the timeline to your liking.

#

That's probably not the best way but it is the easiest. Assuming you're familiar with how animating works.

twin topaz
#

yep

#

but i wanna learn coding and the best to do that is by asking so how would i approach it if i want to code it ?

tropic charm
#

To code it, you'll want to change that same parameter (the camera's size) programmatically in Update().

#

Personally, I would probably use a 3rd party asset like DOTween.

#

If you don't care about non-linear easing then you can easily use Mathf.Lerp() in Update() to get what you want.

twin topaz
#

i pm you how would i improve that code? @tropic charm

native thistle
# tropic charm ```cs float angle = Vector3.Angle(_facingVector, projectileVector); ...

The bullet always faces its direction of travel, but some bullets seek their targets so those ones rotate during their trajectory, yeah.

Could you elaborate a bit more on what you mean by "The projectile rotates so I had to save off its initial direction and use that as projectileVector."? I feel like I'm missing something from your code snippet. ๐Ÿ˜… Either that or for whatever reason I just don't see the whole code.

tropic charm
#

Let me gather up some code to show you what I was playing with...

#

First, here's the projectile (a banana, quite deadly.)

#
using UnityEngine;

public class Banana : MonoBehaviour
{
    [SerializeField] public Vector3 throwVector;

    void Update()
    {
        transform.Rotate(new Vector3(0f, 0f, 180.0f * Time.deltaTime), Space.Self);
        transform.Translate(throwVector * Time.deltaTime, Space.World);
    }
}
#

Note the throwVector field, which I assign when a projectile is created and thrown. (Not sure why I serialized it.)

#
    void Update()
    {
        bool fromTheLeft = Input.GetKeyDown(KeyCode.L);
        bool fromTheRight = Input.GetKeyDown(KeyCode.R);

        if (fromTheLeft || fromTheRight)
        {
            GameObject projectile = createProjectile(fromTheLeft);
            Destroy(projectile, 3.0f); // 3 seconds maximum lifetime.

            if (projectile.TryGetComponent<Banana>(out Banana banana))
            {
                banana.throwVector = fromTheLeft 
                                   ? new Vector3(20f, 0f, 0f)
                                   : new Vector3(-20f, 0f, 0f);
            }
        }
    }
#

So, in this case the projectile come strait from the left or right of the target. I'm scaling the vector to affect the speed.

#

The collider is currently a child of the `target' and is currently doing this... (Which is half-baked.)

#
using UnityEngine;

public class MonkeyCollider : MonoBehaviour
{
    [SerializeField] private Monkey _monkey;
    [SerializeField] private bool _isFront;

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.transform.tag == "Platform")
        {
            return;
        }

        Banana banana = other.gameObject.GetComponent<Banana>();

        if (_monkey && banana)
        {
            _monkey.Damaged(_isFront, banana.throwVector);
            Destroy(other.gameObject);
        }
    }
}
#

Note that it passes the projectile's throwVector.

#

Finally, Monkey.Damaged() does this...

#
    public void Damaged(bool isFront, Vector3 projectileVector)
    {
        Vector2 force = isFront
                      ? _KnockbackForce * _frontHitKnockbackVector
                      : _KnockbackForce * _rearHitKnockbackVector;

        _rb2d.AddForce(force);

        StartCoroutine(ShowDamage(isFront, projectileVector));

        StartCameraZoomAnimation();
    }

    private IEnumerator ShowDamage(bool isFront, Vector3 projectileVector)
    {
        // float angle = Vector3.SignedAngle(_facingVector, projectileVector, Vector3.back);
        float angle = Vector3.Angle(_facingVector, projectileVector);

        Debug.Log("this._facingVector = " + _facingVector + " projectileVector = " + projectileVector +
                  " angle = " + angle);

        _spriteRenderer.sprite = isFront ? _thrownBackSprite : _thrownForwardSprite;

        for (int i = 0; i < 2; ++i)
        {
            _spriteRenderer.material = _hitMaterial;
            yield return new WaitForSeconds(0.1f);

            _spriteRenderer.material = _originalMaterial;
            yield return new WaitForSeconds(0.1f);
        }

        yield return new WaitForSeconds(0.1f);
        _spriteRenderer.sprite = _normalSprite;
    }
#

...which isn't actually using the projectileVector but could.

#

It doesn't use it because there are actually two colliders on the target. One on the left side and another on the right.