#๐ผ๏ธโ2d-tools
1 messages ยท Page 33 of 1
I created the gameObject in the scene in question then saved in the prefabs
Yes
ok
Now the state is that you have a prefab
and you have an instance of that prefab in the scene
Yes
but the prefab has no knowledge or memory of which scene it was "recorded" from
You can parent things to/delete the instance that is in the scene, but not the prefab itself (in the project window)
I remove the gameObject from the scene and replace it with the prefab, is that it?
I don't know what you are trying to do
In fact, I created an NPC that is supposed to open a menu with items to buy, but for that I had to create a prefab of the buttons so that the items appear, but I made sure that the original is destroyed and replaced by the prefabs
But i have this
This is my prefab
And i don't have my other items
And the items are well referenced on my NPC
Waht does your code look like? Usually when I do this kind of thing, I don't even bother leaving a "placeholder" object in the scene
I just let the GridLayoutGroup or HorizontalLayoutGroup or whatever be empty until items are added
I send it to you, thank you for your help
Shop Manager Script : https://hatebin.com/alghsbcduh
Shop Trigger Script (on npc) : https://hatebin.com/ltnsprditp
In your shop manager script - what did you assign to these fields in the inspector?
public Transform sellButtonsParent; ```
ok - Sell Buttons Parent is another reference from the scene?
Or is that from a prefab as well?
OWH ! I got something by modifying SellButtonsParent!
Oh good
I was going to say this setup looks fine assuming the sell button parent is from the scene
But it's break i think ๐
Well it's working you just need to work on the layout part ;D
haha cool ๐
It's not a big game but.. It's a way of thanking kind people like you
@snow willow I changed my prefab and registered, but it does not change ..
I am having problems with 2d pixel sprites. Some pixels are bigger than others. There was someone with the same issue and a person preferred to use a pixel perfect camera. I did and nothing changed. What could I have done wrong?
PPU 32.
Reference Resolution 320, 180
Pixel snapping enabled.
Can you show your problem please?
Uhmm not possible right now.
I will post it later here
No I don't think so, but personally I use a tilemap and it's much easier
But would it solve the "diffrent pixel size" problem
If you use a 200x200 image and another 16x16, it might look strange but they are the same size
Sorry
No problem
I think you didn't understand the problem
I have a 32x32 sprite
Ok ?
And some pixels of this sprite are thin while the others are wide
I found a picture
Pls ignore the art. I improved a lot, but if you look closely you can see that some pixels are bigger than other
And sorry for the bad quality.
For example the white single pixel is bigger than the black one next to him.
Have you set the filter mode to Point(no filter) and Compression to None ?
Yes
๐ฉ
I don't understand what I could hve done wrong.
I don't know either, did you try to re-import the image?
I made a new project. Drag and Dropped the png. Then filter mode to Point(no filter), ppu 32, compression to none, set to multiple then sliced
And then I set up the pixel perfect camera
i also turned off anti aliasing
The sprites are made at piskelapp.com
Did I do something wrong?
I don't know unfortunately I don't do it like this
@pallid lion Look into "pixel perfect" in Unity
I did
Oh I see now. Yea not super familiar with the pixel perfect workflow
You can read above for more information
I already said that I am using a pixel perfect camera, but some pixels are still bigger than other
Hello guys, I made this 2D game and really get stuck in a swapping problem. I want to pile up and down white road s to make a way for a ball to reach the goal. But I am not very experienced so unable to come up with a good logic for this. I have written a code for this in which I am dragging and dropping roads and change their x positions but when I drop road it is not swapped Although I am able to drag so code works but swapping not working. Please, someone, have a look at a code and see where I am going wrong or suggest some better logic for this puzzle swapping. Thank you
Here is the code
https://pastebin.com/timtftik
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Anyone know if there's a way to use rule tiles in the tilemap to generate 1x1 and 2x2 tiles together to make something like this?
Can you just manually cut it?
You would have to set it in a script basically with if statements saying if your player is looking direction x, then do animation z
lol sorry not entirely. I've never worked too much with animations myself, I just know that's probably how you do it.
Check out my latest video! : "Topdown 2D RPG In Unity - 22 Player Stats"
https://www.youtube.com/watch?v=9eh41WPlD_g --~--
In this video, we will be creating the idle animations for our player, and making it so we face the correct direction when we move using a blend tree.
Maybe try and use this tutorial and make a couple different idle animations that come active dependent on which way your character is facing
the pixels from my sprite don't look perfect even after using pixel perfect camera
some are bigger than other
here is a picture of the sprite
Im not worried about slicing, I'm wondering if I can procedurally generate tile patterns using multiple sizes of tiles.
@still tendon are you looking for help on how to do it? i am confused what your question is
Vector2.MoveTowards or Vector2.Lerp is probably what I would use
How do you make it so as soon as you hit the ground the player auto jumps?
Do the jump when you detect collision with the ground, or just on the first frame during which you are grounded
but how do I detect it?
How are you detecting your player being grounded in the first place?
thanks
Hey, what am I doing wrong ?
does the name of your script in engine and the class line match?
like, did you create a new script and then rename it?
yes
Your script name in engine and the script name on this line at the top need to be exactly the same
if not, there are problems
how do you increase the vertical camera size but not the horizontal?
Is it not possible?
What does vertical camera size mean
The main camera up and down
When I try to adjust it vertically it also does it horzontal
I am trying to design a game that goes up instead of right.
nvm I figured it out
Hello! so I was wondering if theres a way to make a few tiles in a tilemap go transparent when the player goes behind it, the only way I can think of so far is to make each tree have its own tilemap to tell if the player is colliding with it
Tbh i dont recommend using tilemap on objects you'll interact with, like: trees, coins, pickups...
There is some things you can do, but the easiest way would be to have trees as separate objects
hey, I'm trying to only detect my floor layer with a raycast for a platformer, but it's still hitting all layers(except ignore raycast, of course).
the code is var layerMasker = 1<<10; hitLeft = Physics2D.Raycast(leftStart, -Vector3.up, GetComponent<CapsuleCollider2D>().bounds.extents.y + 0.1f, layerMasker);
does anyone have any troubleshooting suggestions?
im making a platformer game and its just a square on a single P l a t f o r m,and he dosent respawn,so i need help with the code,i already have the camera following the player and it dosent go up and down so it dosent follow the player while falling to a cold empty v o i d (reply or dm if you can help
hi guys
im looking to make a friend with someone with 2d coding experience, we are making a 2d online game where you can play minigames against other people but need people who are interested in working with me on it as a project
I am making a 2D crafting and dungeon crawler type of game and my character only moves on the x axis and this happens on an Xbox controller as well
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class playercontroller : MonoBehaviour
{
private Vector2 movementInput;
public float speed = 5;
private void Start() {
}
private void Update()
{
transform.Translate(new Vector2(movementInput.x, -0) * speed * Time.deltaTime);
}
public void OnMove(InputAction.CallbackContext ctx) => movementInput = ctx.ReadValue<Vector2>();
}
hey, I need to make a hitbox in my game. The problem is that I already have added the Character Controller and cant add the Rigidbody 2D.
wait do you get an error?
yes
You can't make the hit box with a Collider2D?
for movement is it better to use
rb.velocity = speed * distance;
or
velocity = speed * distance;
whats the point of using rb
show whole code
what you need help with
?? What do you mean by this
Also when would it make sense to multiply speed by distance?
You are missing a return type for your method. void
Methods need a return type in front of their declaration
For OnTriggerEnter it should be void
hey can anybody help me with a collision pls ? Rigidbody 2D doesnt work
Can you be a bit more vague pls? You're confusing me with all that specific informations ๐
I made a game with cars and walls ... the problem is that i can drive through the walls at the moment. But i cant use Rigidbody 2D because I already use the Character Controller ๐ @stark trellis
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float direction;
public float speed = 10f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), 0);
Vector2 direction = input.normalized;
Vector2 velocity = direction * speed;
Vector2 moveAmount = velocity * Time.deltaTime;
transform.Translate(moveAmount);
if (Input.GetKeyDown(KeyCode.Space))
{
}
}
}
how would i implement jumping
My understanding is that Character Controller is only suitable for 3D. There's a 2d controller made by CodeMonkey that is decent, otherwise you'd better make one yourself.
@still tendon add a collider
e.g box collider
or polygon collider if you want to be more precise
make sure its 2D at the end
Character Controller works for me
whats the most popular and most used movement for 2d?
Can someone help.
I get this error:
UnityEngine.Object.Instantiate (UnityEngine.Object original) (at <4a33faade1cf4ef1b3e3a2c4a445e544>:0)
GridManager.generateGrid () (at Assets/GridManager.cs:19)
GridManager.Start () (at Assets/GridManager.cs:14)```
and this is the line that is the problem:
```GameObject refernceTile = (GameObject)Instantiate(Resources.Load("Grass-sprite"));```
I couldn't find a help channel so I think this is the right channel for it ๐
how i should make a responsive for a 2d game?
Optimization question: in my game every Interactable object checks on Update if the Player is in the trigger zone using Physics2D.OverlapCircle, let's say i have 100 Interactable objects in my scene, how expensive is that? Any way i can optimize it/should i?
yeah use trigger colliders instead
that is quite expensive
alternatively, just ahve the player do OverlapCircle on itself every frame to find all the interactable objects near the player
then you just have one OverLapCircle each frame
I'd go with trigger colliders though
initially i wanted to use trigger colliders but my Player has no rigidbody and the interactable objects should not collide with anything except the ground so i set them to kinematic... but this way the triggers don't trigger :/
i did, doesn't trigger
yep
and a CharacterController?
er - rather the CharacterController is the collider
is the player's collider a trigger?
no has kinematic RB, Normal collider, custom controller
i forgot ๐
"Project Settings > Physics > Contacts Pair Mode" to "Enable All Contacts"
you can try that
alternatively just do the OverLapCircle on the player itself
ah there's a enable kinematic-kinematic pairs... interesting but it's under Physics, not Physics2D should i mess with those even if it's a 2d game?
(doesn't seem to have effect anyway)
oh no
that won't work if these are 2D colliders and rigidbodies
two totally different systems
sorry I gave you advice for a 3d game >_>
lol np, anyway i set up the 2d collision matrix this way thinking it would work... it doesnt...
does your player need the kinematic rb?
nah i think it was an experiment, i actually want to remove it
idk sometimes this collision stuff is confusing about what workls and what doesn't
there's a chart at the bottom of that page^
oh my lol, they couldn't have made it more coinvoluted if they tried
yep lol
but actually thanks the idea of using just one OverlapCircle on the player is very good i'll definitely go with that
hi guys im looking to make some friends who are interested in making a 2d game as a team and learn together
feel free to dm me if you wanna be involved, a little experience will help but there are resources to learn from
From the Please Do Not section of this discord's code of conduct
- Post job-posting or make collaboration requests```
hey can sb help me with my code ? There is an error which I dont know how to solve please pm me I will share my screen than
Your funny. Just share your error here.๐
Haha the problem is that I believe that there is more than one error @civic knot
Still. Nothing we can't solve here.
Ok thats the error
The file name and the class name do match so thats not the problem
Errors in the console?
- Go to #๐ปโcode-beginner and check the VS config guide in the pinned messages.
- You need to solve all the compile errors to put that script on a gameobject.
- With your ide configured you will not make stupid typos.๐
But maybe it's not a typo and you actually made a "Vektor2" type ๐ค
okay ๐ well I am doing a 2D game
If it's meant to be Vector2 then you spell it with c, not k. You got it right in several places.
Haha thx german writing isnt good for coding
Vektor2 looks so much cooler than Vector2 though
reminds me of that sports cereal
@still tendon please avoid unsolicited dms, they're against the server rules.
having your ide configured to work with unity will help you see and fix the compile errors in the ide.
ok sry
And you really should've done it when you just started developing. Didn't you notice you don't have autocomplete? ๐
I am Studying how to make games โฆ I dont know how unity works at all. I try to make a game without having the idea of unity or C#
Studying unity and c# is part of "studying how to make games". And a very big part of it.
Anyways, get your ide configured, fix the errors and you should be able to attach that script.
Do you see error highlights in your ide?
What does ide actually mean ? And it didnt change anything so I dont see any error highlights
integrated development environment. VS is an ide.
If it didn't change anything, then it's still not configured properly.
ok its time to give up haha
Did you follow the guide?
yes
take a screenshot of your preferences - external tools and workloads in VS.
You should know where to find these if you really followed the guide.
if you're using VS Code you also need to do all this other stuff <https://code.visualstudio.com/docs/other/unity
Are you using VSc? Looked like VS from the screenshots.
Yes I am using VSc
Then what Vertex said.
hello! this channel is for code but for 2D games? If yes, I'd like to share my problem with you if possible ๐ฆ
Just ask your question
Oh yes sorry ^^
To start, I create a 2D game on Unity. AND, for my game, I have to create a spawner that will make me spawn meteorites and coins. But, here is the problem : at first I had something like this:
and so I wanted my meteorites to look a little more like this:
And, I would like my meteorites and coins to spawn more evenly and closer together, but even by changing the "spawnTime" (which changes the time between each spawn) and the "minDistance" (which is the minimum distance between each object) well, there is no change at all. @hollow crown
The code : https://paste.myst.rs/d20od4wr
a powerful website for storing and sharing text and code snippets. completely free and open source.
@still tendon
In this tutorial I explain how to write a C# script that will allow you to spawn obstacles onto your scene using prefabs and instantiate.
SUBSCRIBE: https://bit.ly/2Js78lE
In this video I will show you:
1:00 Adding a CircleCollider2D, Rigidbody2D
1:37 Adding a script to move the game objects
3:40 Removing objects from the scene onc...
?
I had already tried this but it didn't work.
In fact, so far I've managed to get this:
and I don't know how to make it more random without overlapping
@hollow crown
idk
okay
can someone tell me the 2D double jump script,all the jump scripts i have makes me infinitely jump and i need help
://
reply/dm if you have the script
แตหกแตแตหขแต :โฝ
Let's make a Double Jump with the ability to make it a Triple and a nice object to reset the jump count in mid air.
โ
Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=DEGEEZmfTT0
Simple Jump in Unity 2D
https://www.youtube.com/watch?v=ptvK4Fp5vRY
If you have any questions post them in the comments and I'll do my b...
i was looking for a script but ok :/
in description is the project, just copy and paste the code
but its better to write it by yourself
well if you have time
yea xd
Here is a tutorial that I use: https://m.youtube.com/watch?v=QGDeafTx5ug
In this easy Unity and C# tutorial I wil show you how to make a 2D platformer controller complete with double, triple, quadrupel jumps...
By the end of the video you will have a character ready to take on any platforming challenge he may be faced with !
-------------------------------------------------------------------------------------------...
any of you have already tried to get an enum for scenemanager?
or a popup list in inspector
Hello guys,
I've got an interesting question bouncing around my head since 1 week.
Do yall know what's the visual coding limit ?
I mean, can we do the same thing with Visual coding as C# ?
It's definitely more limited
Can you give me more explanations please ?
it's hard to explain... you have basically absolute freedom to do almost anything when you're writing code
in visual scripting you're limited to the various nodes and functions that are already there
you can combine them
etc..
but you can't just write something from scratch in the same way
Ok, thanks a lot
Also it's a lot easier to use libraries and frameworks in regular code than in Bolt
i'm still a newbie, and I've just found it
you just use them, vs in bolt you have to figure out how to get the API to map into the visual scripting system first
Also if you have more questions about visual scripting, check out #763499475641172029 (actuially a link to a separate discord all about the topic)
Btw visual scripting is pretty easy to use for animations / value check etc
Didn't see it thx
hey I just did a code with a collision, when I hit the Enemys with m y bullets they should disappear which doesnt work ... can sb help me pls ?
Thats the code
Any ideas why the AI's animation is reverse half way through the waypoint? Here's the code for the AI Patrol
does anyone know how to get the line renderer to repeat segments of an image?
i set it to texture mode: repeat per segment
but it just stretches
how many segments does your linerenderer have
i think each segment is the space between two points in the line
If you only have two points, then the whole line is one huge segment
make a continuous line of sprite segments and cut it off instead of stretching it?
uh one sec
lemme dig up a video
look at just
the first like 10 seconds of the video
there's a line between my drone
and the antenna
of blue circles
the texture is just a single circle
but I have it repeating
between like 0:07 and 0:10 of the video you can see it ๐
lemme open the project and check my linerenderer settings
The material looks like this:
did you have only 2 points in the line?
yes
but they're being controlled via a script
private void DrawLineToDrone(Transform drone) {
if (!drone) {
HideLine();
return;
}
if (!LineRenderer.enabled) LineRenderer.enabled = true;
LineRenderer.positionCount = 2;
LineRenderer.SetPosition(0, TipRenderer.transform.position);
LineRenderer.SetPosition(1, drone.position);
}```
what does your texture look like
I want the whole laser to be twisty like in the beginning
on your material
it looks exactly like the first segment of the line here
also you have only two points on the renderer?
yes
it seems to be stretching it after one tile
like once I'm more than one tile away, instead of putting another tile it just expands it
do you have Loop rutned on
turned on*
on the LineRenderer
or Corner Vertices/Endcap vertices?
yeah you don't want loop - although that kinda seems like you have more than 2 points
how are you defining the points for the line
in a script?
are you doing lr.positionCount = 2 as well?
yes
๐ค
I'm at a bit of a loss then...
World Space?
it seems like you have things set up the same way I do - it should work
on
How do I load a sprite from a texture2D by code? In the editor I split up the texture2D (image) to create individual sprites, and I wanted to access those sprites by code. I've seen that a new sprite could be made with Sprite.Create but is that necessary if it's already been broken up?
Does anybody know how to change the color of a 2d point light using a script?
I have a script on my player that used GetComponent<Light> on the light gameobject but it returns null
you need a reference to the light gameobject first to then get that component from it, otherwise unity and your code in general would not know which instance of a light to grab
try making a public Light myLight; field and draggin the light on it, will it let you? if not, then it's not actually a base type of Light
Yeah I tried dragging it in as a light and it said type mismatch
Everywhere I've seen online says to drag the GameObject in then use getcomponent
I think it might be cause its 2d?
ah yeah is it the URP 2D system?
Yeah
try Light2D then
It doesnt recognize that as a class
probably neeed using UnityEngine.Experimental.Rendering.Universal;
Somebody in the lighting channel helped me thanks a lot for the help though
ah okay
Yeah thats what they said I didnt realize I needed to import that
anyone know how to make this more smooth?
the little code
the problem for me it's the bullet spawn in wrong position when i move
you aren't using physics to move these, so move them in Update, not FixedUpdate
FixedUpdate is not bound by the framerate but a fixed physics timestep
@dusty nebula
@dusty nebula The code you posted has nothing to do with spawning the bullets tho
If he's moving the bullets via that code, it sort of is
It doesn't "spawn" them, but it handles their movement, I presume
I put an empty gameobject with an icon parented to the character sprite. Then make a gameobject public' or serielized private' to drag and drop the empty gameobject into that variable in the inspector. Then instantiate the bullets at that variables transform global position not local position because that would be the set constant offset from the sprite its parented to
@dusty nebula i got some ideas
Why sprite in sprite atlas is not packed and returns original texture?
CanBindTo is true though
It looks like atlas doesn't get loaded in edit mode at all. It works in play mode fine
@shell dragon Yeah, the documentation seems to confirm that. No matter the setting, it will never be packed in edit mode.
https://docs.unity3d.com/Manual/SpritePackerModes.html
alright
boys
can u help a guy out
i wanna create a pause menu where there is a restart button. But everytime i try and make a canvas it mixes it up already with another cnavas that I have in the gaeme
is it possible to have 2 canvasses in the game?
Hi
So i want to make my first 2d game (yeah, i know, kinda weird that i can make 3d but not 2d) and i don't know, which template i must choose
2d? Urp?
@north vault 2D. it will download all the 2D stuff automatocally and set it up for 2D. Then upgrade to URP from the package manager.
If you want URP
Ok thanks
does anyone know how I would be able to add controllable vehicle to my topdown 2d game?
How can i create physicsmaterial2d in runtime?
should be able to just do new PhysicsMaterial2D()
Check your spelling
and configure visual studio using the instructions pinned to #๐ปโcode-beginner so you don't make basic spelling mistakes
Where do I configure the visual studio?
you need the same amount of { as you do }
you're opening and closing braces wildly
Why's your FixedUpdate() inside Update()?
both Update and the class needs to be closed
รnete a mi academia de programaciรณn: https://www.hektorprofe.net
Recursos de la escuela de videojuegos: https://docs.hektorprofe.net/escueladevideojuegos
Mis cursos de Python y Django en Udemy: https://docs.hektorprofe.net/cursos
you didn't copy the code correctly
mostly because you are just copying blindly rather than understanding
I already solved it, thank you very much anyway
i have the players arm always facing the mouse and i want the player to change the way there facing when the mouse is on the left or right of the screen can some one link me a tutorial because i cant find one
sorry if that sounds confusing
this ain't working and there are no errors transform.position += transform.forward * moveSpeed * Time.deltaTime;
I was hoping the code would make the game-object move in the same direction it is facing but it is just still
Hi everyone, i have this code that allows me to Left Click a random position on the screen and the character will head to that point, i wanted to add a directional Dash so that the character is able to reach faster the point. I first thought about using coroutines but i get an error where he says: "Couldn't call "Dash" function
here's the code if anyone can help me fix it i'll appreciate a lot
using System.Collections.Generic;
using UnityEngine;
public class MouseDestination : MonoBehaviour
{
public float speed = 2.0f;
private Vector3 target;
private Vector3 mousePos;
private Vector3 objectPos;
public GameObject gameObject;
void Start()
{
target = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
mousePos = Input.mousePosition;
mousePos.z = 1.0f;
objectPos = Camera.main.ScreenToWorldPoint(mousePos);
Instantiate(gameObject, objectPos, Quaternion.identity);
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (Input.GetKey(KeyCode.W))
{
StartCoroutine("Dash");
}
IEnumerator Dash(float seconds)
{
speed *= 2;
yield return new WaitForSeconds(seconds);
speed /= 2;
}
}
}
@final star I think transform.forward is the z axis. try transform.up
did that just then, didn't work
transform.position += transform.up * moveSpeed * Time.deltaTime; like this? (just making sure)
yeah. is the script attached to the gameobject?
Yep other parts of the script is working like intended
Wait, is that attached to WASD? is there any way to move it without pressing keys?
@vagrant wigeon You may need to pass a parameter value to that coroutine (float seconds)
so does transform.up/forward have something to do with keys? I was hoping that it would move on its own, how would that be done?
It doesnt relate to input
hmm... it only works when there is tho
private void Update() {
if (Input.GetKey(KeyCode.W)) {
square.transform.position += transform.up * 2f * Time.deltaTime;
}
}
```I just tried that and it worked
if you want to move without input, just put the transform.position line directly in Update()
oh, square here is a reference to the gameobject im moving
hmm, strange it was in the Update() but I deleted part of the update and it is workin, and with ur transform.position += transform.up * 2f * Time.deltaTime; not sure which one helped tho lol
what part of it do I need to change to acount for rotation?
the pixel art I drew is on a 90 degree angle
transform.left or transform.right instead of up
ohh yeah makes sense
I am slow at this coding stuff I guess lol
hmm... 'Transform' does not contain a definition for 'left' and no accessible extension method 'left' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)
offt
will I probs should rotate it in photo shop or something lol
Transform being capitalized there looks like its referring to the Transform class, not the transform on your gameobject
tysm for ur help ๐
idk if i should put this here but whenever i try to make a project (2d) and then start it, it comes up with this. so please help
anyone?
I'd try reinstalling that version of unity if you haven't already
no it didnt work
hey can anyone help,i need a jump c# script all the ones i tried kept jumping infinitly which will break my game
also a script that removes the sprites off screen to save memory
@hearty oracle do you have a rigid body on the character i don't know much about coding or game development because i'm new but i am taking classes so if you don't have one put one on the character
Check if the player is touching ground by OnCollisionEnter2D
And only if it is on ground you can jump
Hey guys, so trying to have a collision detection to make the enemy's rigidBody kinematic when the player's colliding with them. This is the code I was trying but it didn't even get to the Debug.Log line, so not sure if I'm using the collision detection correctly:
void OnCollisionEnter(Collision collision)
{
Collider playerCollider = GetComponent<CharacterController2D>().playerCollider;
if (collision.collider == playerCollider)
{
Debug.Log("Collided with Player!");
if(GetComponent<Rigidbody2D>().isKinematic)
{
GetComponent<Rigidbody2D>().isKinematic = false;
} else if (!GetComponent<Rigidbody2D>().isKinematic)
{
GetComponent<Rigidbody2D>().isKinematic = true;
}
}
}```
hi, i'm trying to find an object position in unity 2d and i have to put it in an IF, any suggestionsยง?
transform.position @vagrant wigeon
Have you tried using OnCollisionEnter2D rather than OnCollisionEnter?
@gleaming horizon Oh thanks! Missed that ๐
Hello, I need help on how to put two keys for an action, for example space and w to jump, I have configured to jump with space but I want to add the w as I do?
Use input.GetButton and set the settings to the keys you want
Or use
if (Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.W))
Got another question sorry, so the collisions work and everything, and it randomly works. It'll be a Kinematic bodyType (to stop it moving the player and vice versa), then it'll go back to a Dynamic bodyType. The Debug Log keeps going off so I know it's still colliding, I'm just not sure why it's not staying Kinematic. I tried the previous code and this code and it yielded the same results.
This is my code now:
using UnityEngine;
public class RigidbodyExternalForceController : MonoBehaviour
{
public Collider2D playerCollider;
void Start()
{
playerCollider = GetComponent<CharacterController2D>().playerCollider;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider == playerCollider)
{
Debug.Log("Collided with Player!");
GetComponent<Rigidbody2D>().isKinematic = false;
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider != playerCollider)
{
GetComponent<Rigidbody2D>().isKinematic = true;
}
}
}```
It may be that by changing the collider type to kinematic, the collision is no longer detected (there are different rules about kinematic colliders vs non-kinematic colliders), which triggers OnCollisionExit again immediately.
i have the players arm always facing the mouse and i want the player to change the way there facing when the mouse is on the left or right of the screen can some one link me a tutorial because i cant find one
sorry if that sounds confusing
Also you have different if conditions inside Enter/Exit. Is that intentional?
Just check if the mouse X position is < or > than half the screen resolution width
i don't know how to code i just copyed the arm code off of a tutorial
I was trying to see what would work, not entirely sure how I'd go about it if it hasn't got a collision to detect with the Kinematic. I added a Debug.Log to the Exit2D and it didn't reach that, so not sure how it reverted back to Dynamic
WHich object is "reverting" back to dynamic? Which object is this script attached to (the player? an obstacle)?
The script's attached to the enemy, and the player's rigidbody's the one it's referencing. In regards to which is reverting back to dynamic it's the enemy's rigidbody
Isn't that what the code does?
It sets kinematic false
which means the enemy becomes dynamic
right?
The weird thing is setting it to false sets it to Kinematic, setting it to true sets it to Dynamic. Trips me out
๐ค
Are you sure you're looking at the right property
instead of stting isKinematic, maybe set the bodyType?
I tried GetComponent<Rigidbody2D>().bodyType = Kinematic; but the Kinematic was erroring out (same with Dynamic and Static. Not sure what to use in place of it
Ohh ok, I'll have a suss. Thanks ๐
@snow willow It worked! Thanks heaps! Bit of a problem with reverting back to Dynamic upon OnCollisionExit2D. It'll just stay at Static (Static worked for me so decided to go with that):
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider == playerCollider)
{
Debug.Log("Collided with Player!");
GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider == playerCollider)
{
//Debug.Log("Collided with Player!");
GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
}
else
{
GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
}
}```
Hi, I did save on my game, I created a script, I added the SaveAll function: public void SaveAll (), and then I make an empty object and put the scrip on it and add it to the button, but when I put it in on click, it's not SaveAll function, does anyone know how to solve this?
From your description that should work.
Maybe share some screenshots of your code and what you tried to hook things up in the editor?
its now ok
I created a MainVariables script that was supposed to save the state "save game" but broke all the scripts.
what happeing?
when I reloaded unity it broke my scripts but when I took it off the scripts were no longer broken
I have been having trouble getting the player to look at the mouse i got the players arm to do a full 360 i only need the player to look left if the mouse is on the left side of the player sprite and to look right if its on the right side of the player sprite
you should make sure you properly configure VS so it doesn't say Miscellaneous Files in the top left and gives you proper intellisense support https://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity#configure-unity-to-use-visual-studio
how can i add a script to a individual tile rather than entire tilemap
do i just make another tilemap for just a type of tile and add script directly to that?
if i remember correctly you got to go your preference and set your external editor to match what you're using @still tendon
this is my problem, i need the character to jump, by a force aplicated to the orange redtangle (player), but i was checking and it does'nt work.
i think the problem is in how the canJump bool is formulated but idk, i tried my best but nothing, if you want, i can post a screenshots of the code used
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float velocity = 5; //determines the player velocity
public float jumpForce; //determines the force aplicated when "Z" is pressed
bool canJump; //the declaration of the bool canJump
void Update()
{
if(Input.GetKey("left"))
{
gameObject.transform.Translate(-velocity * Time.deltaTime, 0, 0); //if the left key is pressed the player will move left
}
if(Input.GetKey("right"))
{
gameObject.transform.Translate(velocity * Time.deltaTime, 0, 0); //if the right key is pressed the player will move right
}
if(Input.GetKeyDown("up") && canJump == true) //if you press UP and canJump is true the jump function is called and canJump is returned to false
{
canJump = false;
Jump();
}
}
void Jump(){
gameObject.transform.Translate(0, jumpForce * Time.deltaTime, 0); // the only purpose of this function is
} //to make the character jump
public void Collision2D(Collider2D collision)
{
if (collision.transform.tag == "jumpable") { // if you are over a collider tagged "jumpable" canJump will be true
canJump = true;
}
}
}```
Define "it does'nt work". Your code should only displace the character by a minuscule amount per press of "up".
Hi, I have a bug, when I start the game everything is excellent, but when I jump and fall to the ground the character keeps the animation falling, what do I do?
What do you have (see no code, have no suggestion)?
Please refer to this when posting code snippets: #๐ปโcode-beginner message
I put the photos in that section?
Microscopic, I cannot see and copying/pasting code support is extremely tedious with images; nevermind having to constantly alternate between images.
Look at the link, they provide the possibilities.
hey, i updated a bit the code and now it looks like this:
the problem is that when i press "up" it does not anything
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float velocity = 5; //determines the player velocity
public float jumpForce; //determines the force aplicated when "Z" is pressed
bool canJump = true;
bool jumpPermission = false;
public Rigidbody2D rb;
void Update()
{
if(Input.GetKey("left"))
{
gameObject.transform.Translate(-velocity * Time.deltaTime, 0, 0);
}
if(Input.GetKey("right"))
{
gameObject.transform.Translate(velocity * Time.deltaTime, 0, 0);
if(Input.GetKeyDown("up") && canJump == true)
{
jumpPermission = true;
}
}
void FixedUpdate()
{
if(jumpPermission == true);{
Jump();
canJump = false;
}
}
void Jump(){
rb.AddForce(transform.up * jumpForce);
}
public void Collision2D(Collider2D collision)
{
if (collision.transform.tag == "jumpable") {
canJump = true;
}
}
}```
Either insert code here with back ticks or one of the available web services.
If you put a debug log after the call to Jump() does it print?
let me see
Also, are you getting any errors; assuming you're referencing the rb in the inspector.
i had some errors, just wrong-spelling, i fixed them
ok
I already copy and paste in the section that you gave me
i added a Debug.Log("works") and when i open the game, all is ok, then i press up and the console sends a "works" Debug Log almost every frame and my character just go to the space (just floats up slowly)
I do not see any place where jumpPermission is ever reset.
and what should i do?
What's the problem hereb
?
Basically, what you have is a always true condition: ```cs
void FixedUpdate()
{
if(jumpPermission == true);//Always true, but why is there a semicolon here?!
{
Jump();
canJump = false;
}
}
His initial post:
I have a bug, when I start the game everything is excellent, but when I jump and fall to the ground the character keeps the animation falling
Reference: #๐ผ๏ธโ2d-tools message
You need to set jumpPermission back to false somewhere.
Else you'll go flying into orbit as time -> infinity
@runic dirge try to make a grounded bool and and if this bool is true turn the animator "Jump" bool to false cz it stay true after you jumped
how about: "if canJump is false, then jumpPermission is false?"
Maybe just use one of the two bools? Nevermind, you need to keep track of the state.
Yeah, reset them both: ```cs
jumpPermission = canJump = false;
xd
man, idk why it does'nt work.
{
public float velocity = 5; //determines the player velocity
public float jumpForce; //determines the force aplicated when "Z" is pressed
bool canJump = true;
bool jumpPermission = false;
public Rigidbody2D rb;
void Update()
{
if(Input.GetKey("left"))
{
gameObject.transform.Translate(-velocity * Time.deltaTime, 0, 0);
}
if(Input.GetKey("right"))
{
gameObject.transform.Translate(velocity * Time.deltaTime, 0, 0);
}
if(Input.GetKeyDown("up") && canJump == true)
{
jumpPermission = true;
}
}
void FixedUpdate()
{
if(jumpPermission == true){
Jump();
canJump = false;
}
if (canJump == false){
jumpPermission = false;
}
}
void Jump(){
rb.AddForce(transform.up * jumpForce);
}
public void Collision2D(Collider2D collision)
{
if (collision.transform.tag == "jumpable") {
canJump = true;
}
}
}```
can you please link to your code via a service like https://hatebin.com/
i added a Debug.Log("work") in Jump() and it does just work one time and not more
It's supposed to only happen (be called) once. The rb handles the rest.
Maybe your jump force is zero?
it is eighteen
the jump is fine but only happens one time
That's to be expected.
That's how RB is used.
You do not need to interpolate it per frame like direct translation with transform.
@full mirage you need to link to your code via a service like https://hatebin.com/
so, how i made it that you can jump the amount of times you want, not only once in the entire game
yes, jumps properly but only once
The next concern would be your isGrounded state aka canJump
Which you're supposedly resetting in Collision2D.
Which would only be applicable if your object was colliding with another whose tag is jumpable
I'm assuming the floor is tagged with the jumpable string.
I'm saying that you'll only be able to jump once if canJump never gets set to true again.
But you said you could only ever jump once?
And the two conditions to limiting your jumping is either pressing up or canJump. canJump is likely the culprit.
that is true, look:
{
if (collision.transform.tag == "jumpable") {
canJump = true;
}```
Unless you're simply asking "how do you implement a double/nth jump".
Doesn't matter what the code says.
Is it ever occurring?
If not, you will never be able to jump again.
let me use a debug.log
And it will not occur if there isn't a collision . Second thought Collision2D isn't a callback function.
:O
You likely meant to use https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
(First should work but if for some reason.. first should work)
the debug.log is not printing
{
if (collision.transform.tag == "jumpable") {
canJump = true;
Debug.Log("collision");
}
}
}```
What if you put the log outside of the if statement?
when i set it to OnCollisionEnter2D unity launch an error that says it needs to be "Collision2D"
And make it print out the tag of the collider instead
Show the error.
ok
And it should be private.
It says you're declaring it incorrectly.
The link above illustrates that it wants: MonoBehaviour.OnCollisionEnter2D(Collision2D)
Look at their example in the link above.
Quick copy/paste without reading a bit can produce quick results but also easily send hurdles of error your way.
The Collision2D has the collider property if you ever need it||; not likely in your case but if you ever get weird parent-child collider complaints, this is likely the issue. Only the object with the RB is recognized unless you explicitly select the collider's game object - they differ||.
Gratz 
you were so patient, even you expained me how collision works!
thanks and have a great "rest of the day"
guys i have a ques
i animated a ball
when it is moving
and i want to rotate that animation
depends on the postion iam going to
so anyone has an idea?
I don't understand PerlionNoise
Hi everyone i need someone for like 5 minutes because i'd like to ask for advices to simplify a code. If anyone's available pls dm me :)
I need an idea (hint). I have a button, and I think i want to use the UI, which is for start and stop music, and of course it has 2 states, started and stopped. I have 2 images for those 2 states. Which type of UI component do you think I should use?
when u add a component like physical 2dd then u add a polygon 2d thing do u have to save?
pls help
its my first projet an im already stuck
Save the project? Yes
int childamount = level1buildingparent.transform.childCount;
GameObject building = level1buildingparent.transform.GetChild(Random.Range(0, childamount)).gameObject;
GameObject bullet = Instantiate(buildingbullet) as GameObject;
bullet.transform.position = new Vector2(building.transform.position.x, building.transform.position.y);
bullet.transform.parent = bulletspawnarea.transform;
bullet.transform.localScale = new Vector2(0.2577487f, 0.1823389f);
``` does anyone know how to modify this code to shot the created bullet up
how do you handle sub states?
hi has anyone here worked with multiplayer
@drowsy dove if you want to implement multiplayer have a look at mirror its probably the easiest and most secure networking available atm
UNET is severley depreciated
personally i would input a script into the prefab so you can just use the update method
Hey! I would like to know how I can call this function in another script please? Enemy.instance.TakeDamage (); made a mistake.. I know it's because of (int damage) but I can't figure out how to fix this ..
@trim cairn You're supposed to input a int value to the function, so Enemy.instance.TakeDamage (10); should work, for example.
The "Enemy.instance" is a little worrying though. :p
How do I make it go up tho
Thanks !
How is the bullet moving?
You can
Instantiate(buildingBullet, building.transform.position, Quaternion.lookAt(Vector3.up), bulletSpawnArea.transform);
maybe
Change values on the Quaternion.lookAt to make it work
I would like my enemy to display the damage it takes in a float text, everything works fine, but the float text is not the enemy and it activates every time I use my Mouse. help me please?
My float text script : https://hatebin.com/rpksktoetf
When do you want it to happen?
When my player hits an enemy, I would like the damage points to be displayed
And how do you know you hit it? On the code you pasted it was always the mouse is clicked
Maybe the enemy can show the text every time it is being hit
My enemy script : https://hatebin.com/mqloqcjydb
Yes it would be perfect if it worked like that
What is it?
i added fruits to my game
but when i eat the fruits my character doesnt jump and i have to go to another platform to be able to jump again
this happens sometimes
@dense flame It works ! But now I have the problem where my text is not at all at the level of my enemy.
wdym level of your enemy?
@cyan pike we have no idea what you mean by fruits or what the intent is. Please post the actual code and what's supposed to happen in that code. :p
@dense flame my problem
Instantiate (myObject, transform.position, Quaternion.identity);
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
GetComponent<SpriteRenderer>().enabled = false;
gameObject.transform.GetChild(0).gameObject.SetActive(true);
Destroy(gameObject,0.5f);
}
}
}
like this?
I put this in TakeDamage ? @dense flame
You are doing this
Instantiate(damageTextPrefab, enemyInstance.transform)
Change it to this
Instantiate(damageTextPrefab, transform.position, Quaternion.identity, transform)
It works but I think the text is hidden by the snake ๐
Change sorting layer or something
Thx !!
No problem
does anyone know how to make a grappling hook?
anyone here familiar with sebastian lague's 2d player controller video
For issues where you can't tell the difference, I use a site called diffchecker. Especially helpful for following tutorials and comparing blocks of code for the same methods between me and my friends when one works and the other doesn't. Saves time and effort instead of making a git commit or some other difference version control
i will check it out
Hey all Iโm wondering if you guys can help me with some maths code I have to do for college
I need to output the layout number and permutations for that lauding to the screen in scientific notation
What does that have to do with Unity exactly?
Itโs using visual studio within unity
And itโs code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fire : MonoBehaviour
{
public Transform FirePoint;
public GameObject ArrowPrefab;
public float ArrowForce = 20f;
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject arrow = Instantiate(ArrowPrefab, FirePoint.position, FirePoint.rotation);
Rigidbody2D rb = arrow.GetComponent<Rigidbody2D>();
rb.AddForce(FirePoint.up * ArrowForce, ForceMode2D.Impulse);
}
}
``` Um i need help my arrow spins around the player and then after 5 seconds it shoots of into a random direction and i need it to where it fires straight (i have been working on this for 5 hours already)
what does straight mean
when someone likes their opposite gender
Programmers I need help, big help! So listen, atm im creating a 2D mmorpg, on unity. I currently use photon for rooms to join ext, im looking for a reliable option to create one big server that everyone autojoins (mmo will be multiplayer). But, photon only does rooms. ;-;
Does someone have a viable option to make one big server that people autojoin? I use html, css, javascript, c++, c#, java, and python.
Pm please, if someone has an option in will change the course of the mmo
Can anybody help me make code that will do the things in green
Or find a website that will help me make code for what I need it to do .
Itโs using the unity software and visual studio within unity
Does Console.WriteLine even output anything in Unity at all
it looks more like homework
looks entirely unrelated to Unity to me
and certainly looks completely unrelated to 2D coding concepts in Unity
Itโs advanced maths work 2d unity code for my college corse hence why Iโm asking for help
Iโve tried googling the answers but keep running into nothing
lol no it isn't, can you screenshot your Unity project?
So thought I would ask in a dedicated unity group where people would know how I can get the answers
I can try and send a copy of the unity girl
File
Iโm not on my pc any more so couldnโt take photos
I only have the screenshots I took earlier of inside visual studio
Have I done something wrong by asking for help ? The reason Iโm asking is cause Iโve been stuck on this for hours and have been trying to get answers for hours with no luck . Itโs a bit maddening
This is a console application almost 100%,
You are not asking for help, you are asking for someone to just do your entire homework for you
if you want that sort of help, hire a tutor
and don't ask here, in a channel that's entirely unrelated to whatever it is you're trying to accomplish
No Iโm asking for help of like websites and such where I may be able to get the code
Or how I would go around getting the code
And itโs done through visual stupid
Studio
Instead of it being for a video game tho itโs for maths itโs to run mathematical equations in unity
What channel is appropriate to get help with this code ?
#๐ผ๏ธโ2d-tools message
Though almost 100% you will find no help there either
Is there something off about the code that means I wonโt be able to get help with it ?
it looks as if you just want help with homework. that is what your teachers are for
lack of details, lack of relation to unity, lack of context etc etc
|| almost wanna help him to be in that almost section :P ||
Itโs 1 am and my lecturer isnโt active hence why I thought a 2d coding help channel would be a good place to ask for hell
Help
Because I donโt even know what to google to start looking for what code I need
sounds like you need a better time management then
there is no code, the descriptions of what you're trying to achieve either can be easily googled, or are incomprehensible. Additionally each of the problems seem entirely unrelated and without context
also nothing here is to do with 2D coding in Unity as far as I can see?
there's no tilemaps, sprites, etc
just permutations, factorials, and an abstract idea of a level
Itโs being run through unity
I was stumped at : Generate a level.
Bro what you mean generate a level
Through a maths script
I have no idea what that even means
https://www.educba.com/factorial-in-c-sharp/ ok here's a pointer for your factorial function
Thank you
that is if this is actually the factorial that you want
This really needs to move to #497872469911404564
Ah, the "easily googled" part of the descriptions
Is this not classed as 2d code
No. Please move
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Camera cam;
Vector2 mousePos;
Vector2 lookDir;
private Vector2 position;
void Start()
{
position = gameObject.transform.position;
}
// Update is called once per frame
void Update()
{
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
void FixedUpdate()
{
if (Input.GetMouseButton(0))
{
lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
transform.position = Vector2.MoveTowards(transform.position, mousePos, moveSpeed * Time.deltaTime);
}
}
}
why is my spaceship falling when i have my mousebutton pressed? i only want gravity to pull it down when i'm not flying up
You should move with rb.velocity
Or AddForce
If you move with Rigidbody.velocity the gravity wonโt affect it
Yeah he didn't show what gravity is applied to his entire project. Might be a good idea to set it to 0 if he's not expecting to use it at all.
How can i get all collidiers in a radius of a object?
A trigger collider?
no, not trigger collider
circle cast
I've given my tilemap a collider, but now it spins around an arbitrary point instead of the center
How do I change its center?
Using a tilemap and composite collider with rigidbody2d
When I add torque instead of setting rotation it just spins in a huge circle
What on earth
I need help if is possible ๐
Just ask your question
I created a 2D game and implemented a meteorite and coin spawner. My objects move from right to left. So far, I get a spawner like this :
The problem, as you can see on the red line, is that my meteorites are too similar, I would like to have a more random spawner like this :
And I don't know what to change in my code to make something random without it being too much of a mess, you understand? ๐ฆ
Youll need to use another means of generation
Gaussian distribution or some noise as an input
You have a few options
The simples is checking out where the last meteor spawned, and not allowing your game to spawn one on that height again
Sure, paste a snippet and ill have a look
a powerful website for storing and sharing text and code snippets. completely free and open source.
I can also send you my spawner's inspector.
Nah its fine
So I see what you are doing
Any reason to handle it like this?
I would change it for the following if you want the right behaviours (pseudocode incoming)
``
do I put my code in a code block?
Nah pastemyst is better for large chunks
Did you get this code somewhere or write it yourself?
Overall, I wrote it, but I had the help of several people.
Right
The easiest way is, right before you spawn an asteroid
do a check with rectangle overlaps, and see if there arent already 3 asteroids nearby on that height
If there are already, simple try another spawn location
Also keep in mind that the results you are getting right now ARE random
If you want evenly distributed asteroids with equals space before them, simply try a random position, see if it is far away enough from the nearest asteroid, if not try another random positions etc until success, then spawn
oh I see... but I wouldn't know how to rewrite all that in my code ๐ฎ I only wanted to try to modify it or add a few lines :/ @delicate loom
Hey guys I am making a 2D top down game where I control a ball and I have to avoid getting hit by obstacles that are thrown from random directions. My goal here is to instantiate "Obstacle" prefabs at a point and then launch them towards the player. But to actually get the spawn point of my obstacles, I want to get a random angle around my player and then extrapolate the lenght of this direction and then spawn the obstacle to then give it a force towards the player. I'm not completely new to Unity but I am still not really good when talking about vectors... Could anyone explain me how this would be possible?
I am spawning my obstacles in a "ObstacleSpawnerScript"
So you want to spawn obstacle anywhere in a circle around the player?
You can do this to get a random position:
Vector2 randomDirection = new Vector2(Mathf.Cos(randomAngle), Mathf.Sin(randomAngle)); Vector2 obstaclePosition = playerPosition + randomDirection * distance;
and then for the movement
Vector2 obstacleToPlayerDirection = -randomDirection;
thanks mate I'l check that out and let you know if it works as I intended. I will also give a look at Mathf.cos() in the API
Hey there ๐ I'd like to have have a rectangular shape in a 2D game which I rescale during the game. It shall show a symbol on it, though, which should remain it's original size and shape.
Is there a better way than my workaround to have an empty game object which inherits the rectangle and the symbol object?
Is there a more elegant way? Can I achieve this without the emtpy parent? ๐
@neon current It's certainly the most elegant in the sense that it's the simplest!
Meaning you can get fancy with shaders, etc...
But here you have two object with different behaviours so it makes sense to separate them
If you really want to avoid having an empty parent, you can keep just the two object and move them independently ot the same position
Codewise it would be easier to somehow have the symbol as a child of the rectangle somehow.
Yet, the code works, but restructuring it, makes it pretty difficult as I need to change the symbol, when the colour of the rectangle changes. Makes it a bit more complicated at the moment. Kinda struggling right now.
It shouldn't be more difficult one way or another, send code over if you need a quick help
oh no, it disappeared.
It may be helpful to know, why I can't access the child of my empty object.
The hierarchy structure is:
wall_segment
- wall
- symbol
I instantiate the wall segment. And then I want to save its first child (wall) in an GameObject Array but it throws an error. Would show the code, but it did disappear in this chat.
You can try with pastebin
Does anyone know how to make a rigid two-player-only system with the New Input Manager? I don't want to use Player Input Manager, I just want to have the first controller control the already-existing 1st player (left side of the screen) while the next active controller controls the already-existing second player (right side of the screen.)
@limber thistle trying it this way ๐
Assets\Scripts\GameController.cs(172,25): error CS0029: Cannot implicitly convert type 'UnityEngine.Transform' to 'UnityEngine.GameObject'
Ah! It's because transform.GetChild() returns the transform of the child object. So you want to do
wallInstances[i] = transform.GetChild(0).gameObject;
aaaah, so easy ๐ haha, thank you so much! I will try further with my workaround then ๐
Yeah! I should have said something, you can be scaling the box but keep the position on both the box and symbol that way.
Anyway, I hope someone can figure out my quandary. I'm using the New Input System.
Sorry @barren lark I have no idea ๐
Fuccckk hahaha
@barren lark sorry, I can't help you either. But would be interested in how that would work for my question. ^^'
Well, my issue is this. Using the new Input system, most everyone seems to be inclined to having local multiplayer defined like this:
https://puu.sh/Hgcnf/9cefd8776d.png When a new controller is recognized, a new player "Prefab" is created and connected to that input. So, in a game like Gang beasts, a first or second Humanoid is spawned. But this system is so rigid that it's a little silly.
All I want is to have already-existing Player objects that get "possessed" when a new controller is detected.
Also, if anyone knows how to separate keyboard and joystick input across multiple players, make my work a little easier, haha. I'd appreciate that too.
@barren lark unfortunately I have no clue. :/ But could you explain to me, how I could add an image to my scaled object without it being distorted?
How do I figure out if something is above/below/left/right of a position?
I don't need the exact angle
Just something like Vector2.Up
@limber thistle I now made a bit of "dirty" workaround. The thing with the empty parent did not work well in terms of positioning, etc. I know have the symbol image as child object of the wall and before rescaling it, I unparent the wall and reparent it after rescaling again.
it's above if the y component of the position is larger
extrapolate that with y or x for all 4 directions
Yeah if youre still interested gimme like 30 mins
@neon current If it works, great ๐
(but it should works with the empty parent also :p)
@limber thistle it surely would. I just have a specific calculation rescaling and repositioning the rectangle. I would have to recalculate this to the parent, etc., which makes it a lot more complex. ^^
Yeah, so.
Child objects' position are always relative to the parent object IIRC.
So, if I'm envisioning this problem right... You have a wall object you want to scale, with an emblem that keeps the same relative position.
Unity has a Position constraint component you could use instead, it will follow position like a child object, but not be affected by scale
can add a rotate constraint as well. Or use the parent constraint and disable scaling
How can i create a Gui?
Hey there, anyone knows how to make a platform in 2D that you can stand on it and go through it from down?
@remote moth Right click on hierarchy => UI => Button(For Example)
I'm not sure I understand your question but I'm guessing you want to change your sprite's Filter Mode setting to "Point."
but that have i do
and i still have the problem
There must be some other setting causing that then. You might post a screenshot of the sprite's Inspector settings.
@remote moth The Unity version look as though they are .jpg files, where as the first are .png.
and how can i use .png?
The images you made in Paint, save them again but as a png file instead? :p
Don't just change the file-extension from the ones you already have in Unity by the way, that won't change anything.
but it is a png
i never use jpg
i always use png, and i have this problem in unity by all textures files
Dunno either then; settings seem fine.
maybe a dumb question, but how do I refer to a different gameobject within a script? I have two characters, and I need them to be able to interact (like check each others' position), but I'm not sure how to refer to the other one within the first one's script
would I do like
public gameobject otherplayer;
and then just set it in the editor?
That's one possibility, yeah. For just having a reference between objects in your scene it's the most straightforward solution.
awesome
and if I do that, then I should be able to refer to the other player's colliders as well, which was the thing I was worried would be a headache
Something like a otherPlayer = GameObject.Find("Other Player"); would work as well (not adviced). Have some form of manager keep tracks of objects, and reference them through that.
It depends on the situation, really.
And you can reference the collider through the gameObject with something like otherPlayer.GetComponent<Collider2D>();.
that makes sense, thank you!
do you think it would be best to keep it as a public var that I set manually, or should I just do like...
private GameObject otherPlayer = Player2;
because it's not like the 'other player' is ever going to change for each player
Inspector hooking is usually nice when possible, but things that are spawned at runtime generally can't be referenced like that
ahh, okay, that makes sense
Exactly; if you can guarantee that both objects are in your scene at startup, and stay that way it's likely the best way. If you need it to change dynamically at any point you'll need something more.
@remote moth You shouldn't delete your posts once someone has replied to them. That is very poor etiquette.
oh, ok sorry
I'll never make it ๐ฆ
Do you guys know any good basic 2d movement tutorial?
Brackeys
Letโs give our player some moves!
โ Check out Skillshare: https://skl.sh/brackeys7
โ Character Controller: https://bit.ly/2MQAkmu
โ Download the Project: https://bit.ly/2KPx7pX
โ Get the Assets: https://bit.ly/2KOkwjt
โฅ Support Brackeys on Patreon: http://patreon.com/brackeys/
ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท...
Thanks
no problem
Hi new here, I have a unity 2d question. Iโm making a npc ai. The npc moves about and when the player comes in range the npc stops. But it stops on the direction itโs travelling in. So if the npc was going to the right and the player approached him from the top, the npc stops and goes to idle. How can I make the npc face the player. I tried using lookat but that doesnโt work. Any help we be great. Thanks
Can someone help me figure out how to get a 2d camera bounding box?
what's a 2D camera bounding box?
first - what's a 2d camera?
well regular camera
and I want it so that the camera will not show areas outside of where I have content
so a box that the camera view will not go past
you mean like... a fog of war?
kinda i guess
like this
but i can't get this to work
and it's for a platformer
Yeah this seems like a link to exactly a tutorial for what you need
(my games a platformer)
which part isn't working?
In the CameraBounds.cs script you will see 2 field Bounds X and Bounds Y you can change the value and you will see the rectangle in the scene view changing. Set it to your need and itโs done.```
no rectangle appears
Do you have Gizmos enabled in scene view?
okay i'm pretty sure it's on cause i can see the stuff for the camera
uh ok can you share the inspector for the camera bounds object?
like the code for it?
oh
where you can see all the public variables on your scripts etc
yeah
do you see the rectangle when you click on that object?
the one with the bounds on it
ah yeah you have some issuies that you might need to solve before this works..
uhhh
you also have 999+ red errors ๐ฎ
you'll need to fix all that before anything works
CamFollow.Update () (at Assets/CamFollow.cs:12)
when starting out, like a brand new scene, I add a Sprite GO, assign an image to the sprite, and click Play, I get a blue screen, why?
this
in the scene preview I see my image in the center
your camera isn't pointing at your object
look at the game view
and reposition your camera/sprite as necessary to get it into view
something is messed up with your scripts
one of your scripts is not named properly for example
make sure all your scripts have the same name as the class inside
using UnityEngine;
public class CameraBounds2D : MonoBehaviour
{
public Vector2 scaleBound = new Vector2(1, 1);
public Vector2 offset;
[HideInInspector] public Vector2 maxXlimit;
[HideInInspector] public Vector2 maxYlimit;
Camera _camera;
public void Initialize(Camera temp_camera)
{
_camera = temp_camera;
CalculateBounds();
}
public void CalculateBounds()
{
float cameraHalfWidth = _camera.aspect * _camera.orthographicSize;
maxXlimit = new Vector2((transform.position.x + offset.x - (scaleBound.x / 2)) + cameraHalfWidth, (transform.position.x + offset.x + (scaleBound.x / 2)) - cameraHalfWidth);
maxYlimit = new Vector2((transform.position.y + offset.y - (scaleBound.y / 2)) + _camera.orthographicSize, (transform.position.y + offset.y + (scaleBound.y / 2)) - _camera.orthographicSize);
}
}```
wrong one wait
i think this is what the error was pointing to
void Awake()
{
bounds.Initialize(GetComponent<Camera>());
maxXPositions = bounds.maxXlimit;
maxYPositions = bounds.maxYlimit;
}```
@snow willow no matter which way I move it, the sprite doesnt show up in the camera preview
this is a 2D project if that matters
waht's the z position
the default, -10 for both
well there;'s your problem
move your sprite to 0
the camera is put back at -10 so that it can actually see the objects that are at 0
OK, so even in 2D I have to take Z axis into account?
and all newly-added objects are added at -10, basically invisible by default?
it tells me that ```Assets\CameraBounds2D.cs(23,90): error CS0103: The name '_camera' does not exist in the current context
well newly added objects are just added wherever the current object you have selected is... or something like that
but that's what the script i downloaded came as??
nope, even after setting PlayerSprite to Z=0, and creating a new object, it starts at -10. Anyway no big deal, now I know, thanks
that error doesn't even match up with your code though
yeah I don't really know the rules for where it creates objects except maybe "wherever is the least useful or convenient for the developer"
lol
wdym?
I wish it would just create them at 0,0,0 all the time - I think there might actually be an option for that
I mean that on line 23 I don't even see a reference to the _camera variable in the code you shared
public class CameraBounds2D : MonoBehaviour
{
public Vector2 scaleBound = new Vector2(1, 1);
public Vector2 offset;
[HideInInspector] public Vector2 maxXlimit;
[HideInInspector] public Vector2 maxYlimit;
Camera _camera;
public void Initialize(Camera temp_camera)
{
_camera = temp_camera;
CalculateBounds();
}
public void CalculateBounds()
{
float cameraHalfWidth = _camera.aspect * _camera.orthographicSize;
maxXlimit = new Vector2((transform.position.x + offset.x - (scaleBound.x / 2)) + cameraHalfWidth, (transform.position.x + offset.x + (scaleBound.x / 2)) - cameraHalfWidth);
maxYlimit = new Vector2((transform.position.y + offset.y - (scaleBound.y / 2)) + _camera.orthographicSize, (transform.position.y + offset.y + (scaleBound.y / 2)) - _camera.orthographicSize);
}
}```
this code, it's the last statement
well since this doesn't work do you have a better idea?
I don't relaly see why that code shouldn't work
did you copy the Editor folder out of the zip file from that page as well?
Or just the CameraBounds2D.cs?
...just the CameraBounds2D
i don't really know what I'm doing too much
should i just copy the whole folder over?
If you didn't copy the editor folder too, that's why you 're not seeing the box in your scene view
oh okay
there's an editor script in there that is the thing that draws that box