#🖼️┃2d-tools
1 messages · Page 41 of 1
maybe the animation is like just to short and you have to loop the animation
so i need to create a loop for the animation?
i think yes
pls anyone
if you touch anything will add a score, add BoxCollider2d and enable IsTrigger = true;
make a script in the object, ad void "OnTriggerEnter", "OnTriggerStay", or "OnTriggerEnter".
send me a message with more exact info
I need help with Tilemaps in Unity, C# i want to load a preocedural generated world just partial in like chunks, can anyone help me with that?
check dm
i did'nt know all about tilemaps anw
thats sad
isTrigger should be true on the coin, not on the player
yes i mean't that
yeah i know but he prolly didnt know
I believe is the only way to make persisten objects so u gotta work around that
U coul save ur death counter to playerprefs and pull it back it at awake in a New canvas
In the next scene
its ok i find it
Sorry, really dumb question. How can i create a triangle in my 2d project? I cant find it, there are only all the other forms. Ive already searched under --> 2D Object --> sprites.
just download triangle mask image
keep script in that, so add variable "{the up image class name}"
in the collision trigger, add trigger "Take Damage()"
someone already help me ty tho!!
also ask... in movement, when i walk to left, want to flip x the sprite, but my script gave error
how to convert they to a boolean?
forget the bottom code
You need to express what it is you want to check with the if statement
if( what? )
Can you first explain what your expectations for this code are and how they are differing from what is actually happening?
the clipping into the wall
You are modifying the position of your object's transform directly in Update
that bypasses the physics engine
and causes things like clipping into walls
does it work with fixedupdate?
especiaally since you have a Rigidbody, you should not modify the positon of your object directly like that
No - you can't set transform.position directly anywhere
or you will have this issue
For a Rigidbody you should only move it via setting the velocity or adding forces
My square sprite(player), always goes up. I can't get to fix it. I don't have a script for that. I have a rigid body and a box collider component for it.
Can anyone help?
if it's going up it's because
- You have a script moving it up somehow
- gravity is pointed up
- some other force from your scene is pushing it
@snow willow you seem familiar with unity, are you familiar with tilemaps?
oh sad
But I don't have a script for the player movement
How do I make gravity point down?
my character is flying up for some random reason
i can't figure out why
Edit -> Project Settings -> Physics has the universal gravity settings
Where should I change it?
the first setting
Gravity
make the Y part negative
so things fall down
instead of up
😄
Apple didn't fall on newton. Newton fall on applee
if anyone needs help, hit me up im free to help
I am making an enemy that shoots snowballs like bullets (the snowballs move in a line and they don't lose speed). But mine just stops immidietly
Guys I'm so confused how do I make it so that my when my 'Player' touches my 'Enemy' my player respawns? also would I need to make checkpoints first?
Check for collisions on your player script, if the thing it's colliding with is tagged with Enemy, then reposition your player back at some other point.
This is probably a stupid question but how do I do that?
Simply you use a function called OnCollisionEnter2D (collider2D collision) inside it you say if (collision.compareTag("Enemy") and the you respawn the player
I have this code in Visual Studio
its the movement script
but for some reason I don't get a feet transform in Unity.
Did you save the code with CTRL+S
Wait we're working on the same project/tutorial LOL
Also, check for errors in the console when you run.
Finally, could I pls see what you have for the public vars in the inspector by scrolling down.
Can you share a screenshot of the actual script component on your object? It's not pictured in your screenshot
yeah
You need to drag something there
what do you mean
the thing in the script creates that empty slot
it is your job to fill that slot with something in the inspector
can I see yours since u are doing the same project?
Presumably whichever object is supposed to represent your players' feet
I am not doing the project
that was someone else
you likely skipped a part
where they add a feet object to the player
I think it just needs to be an empty object that is a child object of the player
yeah so the player is the parent
but I can't add a child to it
Learn how to make a 2D Platformer in Unity. In this video we look at creating a Player Jump script in Unity which uses Colliders to check if the player is grounded before jumping.
A Unity 2D Game Development Tutorial.
Thanks for watching!
Twitter: https://twitter.com/tyler_potts_
Go check out my main channel: https://youtube.com/c/tylerpotts
...
why not
30 seconds in
is where they add the feet object
yeah
you need to do that part
got it
y
@snow willow I have a new problem. I have changed the code and followed the tutorial but I can't jump. It is the same code as before
Start using Debug.Log and find out if your ground check is working, if your jump button check is working, etc..
how do I do that
Can you give me an example
Debug.Log("Hello!");
but y would I do that?
that would just print out something in the console
indeed
To diagnose your problem
to figure out why you can't jump
i will try
For example, put one of those inside the Jump function around line 31 to make sure it's actually running
Start thinking like a detective 🙂
I don't see anything in the console
then that code isn't running
you've learned something
how do I fix it?
ok
Looks like it's being called inside an if statement on line 18, right? And that if statement requires both isGrounded() and Input.GetButtonDown("Jump") to be true. So maybe print out the value of both of those things to see what's going wrong?
any good free pixel art and/or 2d art drawing programs?
ok thanks!
Aseprite is good tho
it cost money tho ://
Buy Aseprite to support its developers:
https://www.aseprite.org/
Download Links:
-
Aseprite official GitHub repository:
https://github.com/aseprite/aseprite -
Visual studio community version:
https://visualstudio.microsoft.com/downloads/ -
Aseprite Source Code:
https://gith...
But if you ever have the money and time, I reccomend you buy it too. To support the developers of aseprite.
(This is actually how I first got it.)
thank you!!!
Np :D
Hello i'm new, i wanna learn Unity and use the CCG TGC Kit, someone know how i can fix the layout from the Cards?
Aseprite gets a very good tilemap feature soon, im hyped af
Hi everyone, I have a question on what the best practices are to setup a character controller on a 2D platformer-like game, namely on how to link the behaviour of the current state of the player (idle, walking jumping wall grabbing etc) to its animation. I setup a state machine pattern for the main character script, and then use trigger variables to swap between animations on enter/exit states. I know it is also possible to simply add code to the animator state itself (which I dont do). How do you usually do it?
i made it with the animator itself like if my movement variable which was linked to the Axis of horizontal was higher or lower then 0.1 or -0.1 it changes the state
hi i am new to unity and as my first project i wanted to make a 2d ragdoll game and i want my ragdoll to be pickable and throwable like in mobile game beat the boss using a tutorial i made my ragdoll https://generalistprogrammer.com/unity/unity-2d-ragdoll-character-tutorial/ and using a tutorial i made grab and drag mechanic https://www.youtube.com/watch?v=55TBhlOt_U8 but when i grab a part of ragdoll the other parts of the ragdoll go crazy how can i solve this
Unity 2d ragdoll tutorial,learn how to make a character and make your character move and walk animations using ragdoll physics, hinge joints and rigidbody
Learn how to drag a 2D object with the mouse. In this tutorial we will create at general drag-and-drop script you can use on any sprite.
····················································································
♥ Subscribe to Oxmond Tutorials:
https://bit.ly/SubscribeOxmondTutorials
● Download the free Japanese Dishes sprites here...
does anyone have a good method for having a sprite update the max value on a slider?
sprites are just image files
You can update the max value on a slider by setting this property https://docs.unity3d.com/ScriptReference/UIElements.BaseSlider_1-highValue.html from a script
I tried this and the max value goes up but not the slider maxValue
if (LevelManager.instance.maxHealth > slider.maxValue)
{
slider.maxValue = LevelManager.instance.maxHealth;
}```
I figured it out
Another good pixel art software is UPA Toolkit by Brackeys
I'm trying to get the Cinemachine camera to follow a gameObject that is tagged with "playerTag", but it's not working. Here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using Mirror;
public class CameraManager : NetworkBehaviour
{
string playerTag = "Player";
// Start is called before the first frame update
void Start()
{
GameObject newPlayer = GameObject.FindGameObjectWithTag(playerTag);
GameObject.Find("CM vcam1").GetComponent<CinemachineVirtualCamera>().Follow = newPlayer.transform;
}
}
What happens? Errors?
Doesn't give off any errors, just doesn't work
Check if Follow is set after that runs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using Mirror;
public class CameraManager : NetworkBehaviour
{
public GameObject newPlayer;
public Transform FollowPlayer;
private CinemachineVirtualCamera vcam;
// Start is called before the first frame update
void Start()
{
CinemachineVirtualCamera vcam = GetComponent<CinemachineVirtualCamera>();
GameObject.Find("CM vcam1").GetComponent<CinemachineVirtualCamera>().Follow = newPlayer.transform;
}
void Update()
{
if (newPlayer == null)
{
newPlayer = GameObject.FindWithTag("playerTag");
if (newPlayer != null)
{
FollowPlayer = newPlayer.transform;
vcam.LookAt = FollowPlayer;
vcam.Follow = FollowPlayer;
}
}
}
}
I tried this to fix it, but it still doesn't work
This is so it automatically finds the player with tag playerTag
Yea, just meant check if the field is set when you do it in code
And it points to the right transform? What if you set it manually?
Ill try that
Nothing still happens when I set it manually, because nothing changes
So the camera rig isn't working?
I meant change the Follow field on the camera, not on the script
And make sure the value is on the camera as expected
Oh okay one sec
That works but every time I disconnect from the server and join back it stops working
I'm using Mirror for the networking
Now check if the script is setting the value
It is
So the value on the camera is the same as when you set it by hand?
Then I have no idea 😄
When I leave and join back this field becomes empty, is there away to have it automatically set into this field and not the scripts field?
This one stays filled in
It stays filled or is refilled?
refilled
Yea what you are trying to do is the way to do it. Not sure why it isn't working
ah when i see the name brackeys i know its good
I got it working, but when I spawn in another player It doesn't work for the new player
do you know why?
I'm going to bed, hopefully a solution will come to me when I wake up, lol
@unique turret Are other players also tagger with playerTag?
Yeah they are
I just spawn in the same prefab for every player
Then the FindWithTag is probably problematic
Alright so what should I use?
I would consider moving this sort of logic to the spawner, which could set up the UI target, camera target etc
On the spawner you can probably figure out when you are spawning a GameObject that belongs to the player
Alright thanks, I'll try some stuff in the morning
does anyone have any good tutorials on 2d isometric games? I'm a beginner, and I'm just trying to figure out this game style nothing fancy
im tryna set up colliders on a tilemap right now and im lost
Hello, I got a question regarding the Pixels Per Unit Setting.
I have a 100x100 pixels Sprite and imported it into Unity. I left the PPU setting at 100.
My understanding was that the Sprite should now be 1 square Unity Unit in Size, however it seems it is only 0.5 units wide and 0.5 units tall.
What's the problem here?
i got da collisions working 
can someone help me i need to learn how to make a 2d object move randomly and when it hits the corner or something thats a fance itll go the other way
give it a random speed between idk -5 and 5 on x and y axis and add a bouncy material, should do it
hello! im making a chess app with unity. but i dont know how to code it. :/
Hey! Does anyone know of a way to render two scenes at the same time, transitioning from them left to right ?
[ scene 1 ][scene 2]
CAMERA -->
Composite two Cinemachine cameras together
Thanks! Will read up on what Cinemachine cameras are and how they work
Cinemachine is really cool, I highly recommend looking into what it can do
So the fact that the two cameras i'd have to composite together would be in two different Scene hierarchies is not going to prevent me from doing this?
https://www.youtube.com/watch?v=2jTY11Am0Ig this seems to be a pretty good intro
Let’s put a camera on our character!
● Check out Skillshare: http://skl.sh/brackeys9
● Instagram: https://instagram.com/brackeysteam/
● Watch Player Animation: https://youtu.be/hkaysu1Z-N8
● Download the Project: https://github.com/Brackeys/2D-Camera
● Get the 2D Sprites: https://bit.ly/2KOkwjt
♥ Support Brackeys on Patreon: http://patreon....
I made a inventory for 4 items, everything works just fine, but I also have a script for item to follow player and theres a problem. I want first picked up item to follow player, next 3 to disappear from scene and the rest to stay, but instead first 4 items disappear, 5th starts to follow player. Can you please help me? I recently started Unity and Im not that good.
How do i make tilemap spikes bloody when an character steps on it and dies
Hello, 2D I'm developing a mobile game, I want my character to apply force to the position that the player clicks. How can I do?
Hey! I was wondering how I would make a game that I'm working on similar to spore where I can drag and drop parts on a 2d character in order to affect appearance, movement damage, health, etc?
I have a character
And pieces
Spore's character creator is quite complicated
Keep in mind Spore had over 100 developers, 8 years of development, and they still had to simplify their final version of the character creator from their original idea
Man what a disappointment that game ended up being lol
😦 still have the box. If only
I only want to be able to click and drag onto body
And be able for it to carry on throughout scenea
Scenea*
Scenes*
Then you just want to Instantiate some sprites as children of the main body I suppose
My particles (in a 2D project) are showing up in the editor (when selected) but not in the game preview
Has anyone experienced something similar and know how to resolve this?
They have Play On Awake checked? Or if not, you're managing the Play() through a script?
Do they have Loop checked (if they should loop)
Oh also, are you running your game when doing this. If the game isn't playing the particles won't run in the game preview
Yes, play on awake and loop checked, playing the game inside Unity
So weird...
No background, so they aren't being hidden by a layer or something
Can you try swapping the material for a moment or something? Are your particles maybe transparent, or something else that would prevent rendering
Changed to Grid instead of Spites, no change
my 2D collision isn't working 😦
Is there a way to hide certain types of objects in the game preview, or something?
I have 2D Box colliders on both objects, but nothing shows in debug
@left lotus Found it 🙂 I had for some reason set Z Y and X positions to some weird values
haha nice
lol!
for OnTriggerEnter2D, you need both objects to have 2d colliders and one to have a rigidbody right?
I'
I've done that, but it is not occurding
The triggering one has isTrigger checked, and the one with a RigidBody does not have isTrigger checked, is that right?
Is the RigidBody on the same object, or a parent object, of the Collider?
And is the script with OnTriggerEnter2D in it also on the object with the trigger-Collider?
Also confirm you don't have the objects at different depths (z value)
Is there any way to remove this annoying twitching whenever I instantiate a prefab inside a Scroll View?
It looks like the messages have an animation to quickly slide-down-from-up into view
Is there any kind of animation or anything on them? If not, how are you instantiating them inside the view
I have prefabs with empty text and I fill them up with the message text after setting SetActive to false as soon as I instantiate the prefab. Then I set SetActive to true to make the message appear on screen.
I'm not using animations/tweening at all in this case.
Ok so i tried to follow brackey's 10 minute making a video game Video and um, i don't know what i did rwong. Can someone explain?
second image: brackey's. third image: my code ._.
Your code doesn't match the brackeys image? Also the brackeys screenshot is from an incomplete portion of the code that won't compile until he's finished typing
Oh
So to make a 2D game, i need to:
-rwite info on paper from start to finish
-git gud at speedrunning
aloha
i need help
i cant find the condition tab in my inspector
how do i add it?
conditions are part of transitions
which are the arrows between your states
Looks like if you make setactive true then later the layout system starts to place to the correct position (based on size). You could try yourRect.ForceUpdateRectTransforms(). But I am not sure which rect you need to use there after using SetActive(true).
Also you can do LayoutRebuilder.ForceRebuildLayoutImmediate(parentRect). This should force the layout system to rebuild. Better try this first.
Ok, let me try.
Oh, wonderful. The twitching disappeared after adding LayoutRebuilder.ForceRebuildLayoutImmediate(parentRect) Thank you so much @brittle helm !
hi again i realised unity is too much for my dumb brain so yea adios
Hey, I have a question: I have some rough controls to move my player by swiping. But it doesn't move until I let go of the screen. Is it possible to regulate the way that he moves swiped after a real distance?
https://pastebin.com/LCvzGTDu
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.
Lines 48 and 52 you have 'if' statements for touch.phase == TouchPhase.Moved and touch.phase == TouchPhase.Ended, all of your logic is happening when touch.phase == TouchPhase.Ended
You want to move it into the (touch.phase == TouchPhase.Moved) region, but then you'll need a little bit more code a the top to check if the distance is above whatever distance you want as your threshold
yeah i know but i dont know to start. so do u have an idea? and thx for the answer
i want to make an animation for a walking leg does anyone have a good tutorial
It depends on what type of text mesh pro component
Think this is where I put this.
I got my Tile select cursor working. It's just not working when I hover it over the main tiles.
I can see and move my cursor hover over the empty space, but doesn't show when I hover it over the main tiles. Not sure if I coded wrong or just have terrible layers.
I know how to use a shader to outline a sprite. How can I outline a composite object consisting of several sprites?
When I place a text it's just blurry and when I go to the game view it isn't there can anyone pls help me.
never mind I figured out my problem
how can i make a 2d block follow the cursor
Anyone knows if it's possible to use a render-texture as a sprite? I'm working on a sprite-based game, and I have some 3D elements I'm rendering in real-time using a separate camera into sprites. It works if I just apply the RT to a quad, but I'm wondering if I can use it with the sprite renderer? That way they'd act consistent with the background sprites order in layer and 2D lighting and such
How could i make a timer that starts counting everytime you take a potion and when like 5 seconds are over then the effectes disappear?
Look into using a coroutine
pls help
Due to the nature of Tilemap Colliders, I must do this
I do not wish to do this
give me a wiser solution
(but i will totes do this for an alpha cuz deadlines)
if I could magically select certain tiles's specific colliders to enable/disable in a tilemap collider
that would be wonderful
I have a problem with my 2d game. I want to make an ice block that has 0 friction but I can't make it work. I have tried adding a physics material 2d with 0 friction but it didn't work. I added 0 anglular drag in my player, I added a rigidbody on the tileset and set the angular drag there to 0 and it still doesn't work. I don't know how to do it
Anything look wrong with this code? Essentially, it puts a raycast2d on a player (down from their feet) to check if there is ground below them, which is represented by the bool grounded.
Essentially, grounded is never set to true when I run the game despite the if statement there. I am wondering if there is anything wrong with this code that could be causing this
As can be seen by the red debug lines, the raycast is colliding with the tilemapcollider (green)
Thanks in advance for any help
anyone know how to setup A* from arongranberg with Unity's grid system? setting the cell sizes to the same value in both won't result in an overlap at all.
Basically grounded = (hit.collider != null) which would imply hit.collider == null if the lines are red.
Thank you
So there weren't any valid colliders hit during the raycast.
Brackeys tutorial
nobody? :[
sick of playing sorting layer roulette, but guess it'll have to do
Hello, I am having trouble with adding a jump movement. I want it to only jump when it is on the ground. So I tried adding a groundCheck feature. But now, I can't jump at all. Here is my code. Can anyone help?
Is the ground check working? Debug values by logging them or using breakpoints in Visual Studio
lemme try that
Wait @vocal condor , I am a little bit confused. I think I get what you are saying but what makes the collider not valid? Sorry
If they do not have the correct layer that you're filtering for.
Being trigger mode may effect this as well depending on your global settings.
QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal
public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);```
queryTriggerInteraction Specifies whether this query should hit Triggers.
Ok thanks I got it 👍
Still haven't figured out a good solution for this camera, I'm using Mirror to spawn them in, The red square is the place where I select what prefab I want to be spawned in when the player presses play
You should be able to handle the spawning yourself in your network manager. You can probably copy the implementation from the base network manager to start with
Is now someone here who is familiar with tilemaps and could help me to get a chunk system in my tilemap so its not loading the whole tilemap?
IDE setup is pinned to #💻┃code-beginner
k
fellow devs
I need help
this isn't showing up in my game
scene view its there
game view its not
however the trigger still works
and I can still pick it up
is it meant to be 307 units away in the Z direction?
I imagine it's just not in your camera's clipping planes
this also isn't really a code question
you were very correct
and I thank you
additionally, where would something like this be appropriate?
Hey, does anyone know how to make a simple 2d lever? when the player walks to the right the lever switches to the right sprite and when he walks to the left, if switches to left one but i cannot seem to get it to work since on TriggerEnter2D dosent have contact points and i am using that to check when the hit location is... and if i use collider it just kind of bugs out and its not the way i want
hi, I am trying to get only the rotation of a vector so that my character will always run in the direction its going, here is the code that I have so far, but I dont know how to get only the direction of the vector
Vector3 direction;
void update()
{
direction = GetComponent<Vector3>();
direction = Quaternion.LookRotation;
}
when I do that, it brings me the error "Cannot convert method group 'LookRotation' to non-delegate type 'Vector3'. Did you intend to invoke the method?"
so can anybody please help me?
does anyone know to make UI buttons stack vertically, so that if a button in between is disabled, the one above will move to stick to the one below?
but did you wanted to invoke the method. did you wanted to do this ```cs
direction = Quaternion.LookRotation();
instead of ```cs
direction = Quaternion.LookRotation;
Look up vertical layout group and sibling index
there's a lot wrong with this code snippet... what eactly are you trying to get the direction of @still tendon
- update should be capitalized
- Vector3 is not a component
- is
directionactually a declared variable anywhere?
Hey guys, I need a lil push into the right direction. I'm trying to have it so that I have an object attached to the player which rotates around the player based upon the mouse's position on the screen. I want object to collide and stop on things within the environment without trying to phase through and/or fling the player around (like "Getting Over it").
It would be great if someone could redirect me to a source that could help me.
Here's an image of what I mean :
I've tried the following
void Update()
{
transform.position = player.position;
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
}
But I have the problem of the "Stick" simply phasing through objects like its Martian Manhunter. Instead of colliding and Stopping
you're going to need to use a physics-based solution. Modifying the Transform directly is going to completely ignore physics, as you have seen
can you think of any solutions off the top of your head that I can look into?
A rigidbody on a hinge joint probably
So I can keep the script the same but put the "stick" on the hinge joint instead of just your standard child/parent relationship?
modifying the rotation of the transform directly in your script is not going to work
no
Hi, does anyone know a way to "pixelate" a Line Renderer ? I think my best solution could be a shader ?
Yeah a "pixelated" shader would work nicely
thanks but I realized that doing that isnt gonna work, so I found a way better and simpler solution, which in short is just making the detection float for when to switch animations a bit higher and that did the trick😂
I ended up using a render texture, it is even simpler
I have a problem with my 2d game. I want to make an ice block that has 0 friction but I can't make it work. I have tried adding a physics material 2d with 0 friction but it didn't work. I added 0 anglular drag in my player, I added a rigidbody on the tileset and set the angular drag there to 0 and it still doesn't work. I don't know how to do it
unity somehow can see 5 errors but i have been looking at this script over and over again and i think it looks fine
What are the errors?
I'm very new to Unity and setting up games in general. I just set up a collision box around the camera so objects in the game don't go off the sides of the camera out of view, but if I change the aspect ratio to 4:3, the collisions boxes stay the same and objects can go off screen from the sides
@still tendon Look into this: https://www.youtube.com/watch?v=M7v1TGQnJ7I
Watch this video in context on the official Unity learn pages
http://www.unity3d.com/learn/tutorials/topics/2d-game-creation/confined-follow-camera-cinemachine-2d
In this live session we will explore worldbuilding in 2D using Tilemap and 2D Cinemachine. Tilemap makes it fast and easy to create and iterate level design cycles right in Unity, so ...
That covers how to setup Cinemachine cameras to nicely follow along 2D and confine themselves to an area that shouldn't differ by screen ratio. If you want to prevent the character walking off too you just have to throw some colliders around the edge
The game doesn't have a moving camera, so that doesn't really help me, but it was useful to watch still so thank you 🙂
Oh, ok 🙂 I guess I don't understand your description of what you're trying to do then
Hello, so essentially I am trying to make an enemy in a side scroller walk and then turn around when they hit a wall. This is what I got so far does anyone know what is wrong with this code?
Right now the enmy just jitters in place atm
@tidal onyx For one, you can just do movement = direction * speed * Time.deltaTime
Second, what happens if you replace translate with just altering the position manually?
Would something like this work for changing the position manually?
this.transform.position = new Vector2(transform.position.x + 1, transform.position.y);
You can just do transform.position += myVector
In your case transform.position += movement
You dont need this, the this is inherent when referring to stuff in the class scope
Hmmm... I get the same result. Basically the game object just vibrates back and forth. I assume that is because the raycasts are hitting the collider too early?
Do you have a rigidbody or anything else on it?
Although I dont think the game object is not close enough to the collider to trigger it, so idk
Yeah I have a rigidbody
Is gravity on?
Here it is
What happens if you set gravityScale to 0?
I get the same thing
if you remove the rigidbody wha happens?
Unfortunetly the same result
Wait actually, that if statement seems weird
Are you trying to say if one of the raycasts is over the side of the platform or something it flips?
You originally said when they hit a wall but you're raycasting down
So they are raycasts on each side of the game object and yes I am intending for them to flip when they hit a wall. I'm using raycasts instead of OnCollisionEnter because the environment is a tilemap so it all has the same tilemap collider.
I see the issue you pointed out with the raycasts being .down, what should I change that to?
.right and .left?
Yeah because right now its like youre checking if its grounded
Since both raycasts are pointed down im assuming its always triggering
Ok, I got the game object to move! The only issue is, when the raycast touches the collider, that if statement gets caught in an endless loop. Is there any way to get around this?
What do you mean by endless loop?
So basically right now the gameobject moves, and when it encounters a wall it gets stuck there. What I think is happening is the raycast is colliding with the wall collider, starting the if loop, and turning around the game object, however since the raycast is still touching the collider when this happens, the if loop executes again and so on, going on forever
Oh. Do
direction *= -1;
transform.position += direction;
multiplying by -1 is the same as scaling it
The reason its happening is because time.deltaTime is not consistent so its probably getting caught
oh is it vector2 to 3?
No everything should be vector2
It says the operator += is ambiguous of types vector2 and vector3
Yeah you cant add v2 and v3, adding (Vector3) in front converts the vector2 into a vector3
Since transform.position is always a v3
Need help with something; -;
Assuming I have a clock in the scene (whose hands are already running) if a bool becomes true, the minute hand should be "fired" in exactly the direction in which it is pointing.
How can I do that?
Hi, I'm probably asking a stupid question, but is there anyway to create more than one Rules Tile with the same tiles? Basically I have this tile: https://files.fm/u/3gzr8yxt3#/view/u7csgnyn8 and based on the dimension of the rectangle, I want to use part of it. I'm thinking I have to create different Rules Tile and use each one appropriately, correct?
Other question: can two tiles with the same rule coexist?
Check if the bool is true and then add a force to the minute hand
hey there. quick question here. I'm using a Tilemap and I have registered and rendered a few tiles through code. My problem is that the images are too large, I need to know how many pixels the tilemap draws per unit. How can I get this piece of information?
Unity 2020.3.2f1
Got it, it all depends on what value I give as pixelsPerUnit when I create the sprite
Hi, I was just wondering how do you get an instance of a GameObject to reference itself in code. It's fine to do with GameObjects where they are the only ones with a certain tag but with enemy bullets for example I need it to reference the exact one I'm using and not the prefab or anything else.
Not sure if I'm making sense with this but it's pretty hard to explain 😓
If you have a script on a prefab, when you instantiate that prefab, it creates a whole new GameObject and the script that runs is relative to that single instance of it.
So would my option be to just set the GameObject to public and then drag and drop my prefab into that in the Inspector?
That depends entirely on what you're actually trying to do
I'm trying to access the SpriteRenderer and Transform components so I can alter them in code
So you want to create a reference to the SpriteRenderer in your script, and either drag it in the inspector or use GetComponent<SpriteRenderer> in your Start() method.
Transform you can just call with the transform reference
Can I change the scale of the sprite using the transform reference?
hi, probably a stupid question but, is there a way i can read how much pressure is being applied to a Rigidbody, i can't seem to find anything helpfull online.
Closest you can get is the impulse from any collisions:
https://docs.unity3d.com/ScriptReference/Collision-impulse.html
But of you're talking about fluid pressure or something Unity's physics engine doesn't simulate that
thanks
this is my first video and it's about 2d jumping in unity!
i accidently put my scene to hexa in the tilemap. how do i change it
strg Z doesnt work
nvm
Hi guys I have this problem, I want to put a character but my world is a parallax that is always in motion, so it gets out of place and the effect is put on the sprite. I have more bug, does anyone know what I could do? I have no idea
Working on an isometric map, just followed a guide by Adam C Younis. My tiles with higher Z are drawing below tiles on the same grid space with lower Z values. Mode of tilemap renderer is set to individual, sort order is on top right.
how do i make a script that will run some code if all the enemys in the layer is gone
Do you have some kind of enemy factory that would be able to watch for that condition?
Hey I need some help regarding UI ordering in unity 2d. So we got a setup where there are platform gameobjects in the world and a canvas instantiated under it as a child, basically to make a setup where an object has a text attached to it, and the player character can climb over it.
The problem is that the UI appears over everything else; we don't want that, we want the text to stay behind the player character. I am not sure how to proceed on this one- should I make a single canvas for the entire scene and replace all the texts? mess with the layers in canvas/sprite renderer?
Here is a screenshot. The text should appear under the player character but over the dark brown box.
and the "canvas instantiated as a child of game object":
Screen space UI will always draw over world space objects. Use a world space canvas or a second camera with screen space camera UI on the bottom camera and the 3d object on the top layer
can you elaborate on the second method? It seems like world space canvas is a bit too large
nvm, fixed the issue by just making an empty child and adding textmeshpro component to it (and adjusting sorting layer). thanks for the help!
hi, i was hoping someone could help me with how i make the character animation only happen when they are moving? thanks!
I'm currently trying to generate a checker board and I can't figure out why my color isn't generating properly. I'm getting this when the desired effect is just a normal-patterned checkerboard. Can anyone help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Board : MonoBehaviour
{
public GameObject mCellPrefab;
public Cell[,] mAllCells = new Cell[8, 8];
public void Create()
{
for(int y = 0; y < 8; y++)
{
for (int x = 0; x < 8; x++)
{
// Create Cell
GameObject newCell = Instantiate(mCellPrefab, transform);
// Position the Cell
RectTransform rectTransform = newCell.GetComponent<RectTransform>();
rectTransform.anchoredPosition = new Vector2((x * 100) + 50, (y * 100) + 50);
// Setup
mAllCells[x, y] = newCell.GetComponent<Cell>();
mAllCells[x, y].Setup(new Vector2Int(x, y), this);
}
}
for(int x = 0; x < 8; x += 2)
{
for(int y = 0; y < 8; y += 2)
{
// Offset every other line
int offset = (y % 2 != 0) ? 0 : 1;
int finalX = x + offset;
// Color
mAllCells[finalX, y].GetComponent<Image>().color = new Color32(230, 220, 187, 255);
}
}
``` This is the code I'm using to generate the board
And I highly doubt the problem lies in my Cell class but here's the code for that too ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Cell : MonoBehaviour
{
public Image mOutlineImage;
public Vector2Int mBoardPosition = Vector2Int.zero;
public Board mBoard = null;
public RectTransform mRectTransform = null;
public void Setup(Vector2Int newBoardPosition, Board newBoard)
{
mBoardPosition = newBoardPosition;
mBoard = newBoard;
mRectTransform = GetComponent<RectTransform>();
}
}
Nevermind, I found the problem
My second nested for loop should've been y++ instead of y+=2
the window is a child of the upper most canvas.
hey, i just wanted to adjust the hight of a coin in my game. But when i click on the coin the inspector just shows a preview:
but when i did this yyesterday it showed me the stuff with high and xyz
how do i get back to this inspector
I think you were looking at the sprite settings for the coin
You've clicked on the sprite, not a game object that is using this sprite
or that
Anyone figured out how to get Z Axis working properly on an Isometric tilemap with chunk rendering? I've set up sprite atlasing and set Trasparecy sort mode but that hasn't helped...
how do i click on it as an object?
From the Hieracy widow, find the object you put your coin sprite on, then press that object to adjust the positioning with the inspector window
hello, I have a question.
this should be 2D, but when you turn your player model, it changes the prespective a bit? or is it an ilusion haha
transform.rotation = new Vector2(transform.rotation.x, transform.rotation.y, 0);
Anything wrong with this line?
If there is, how do I go about changing the rotation/direction for something?
Rotation is a Quaternion
Also Vector2 only has 2 components, did you mean Vector3?
If you want to set rotation as a Vector3 use transform.eulerAngles @tidal onyx
Same for reading it
My game is top-down so I guess I meant vector 2
I only did 3 values because there were 3 in the inspector, my bad
eulerAngles is a Vector3
You will have to use Vector3
If it's 2D most likely only the z axis rotation matters
Hi there. Quick question: https://docs.unity3d.com/ScriptReference/GridLayout.CellToWorld.html
Does it return the center of the cell, or one of its corners?
what would be the best way to have a drag to rotate system?
I've tried doing it myself, but the object just keeps spinning
I haven't been able to find a good answer through googling... I have a number of GameObjects with a BoxCollider2D each, and scripts with OnMouseDown functions. If these objects overlap, what decides which of them get the click?
Currently it seems that one of my objects that's the largest but also has a Order in layer of 0 whereas the other objects have 1, 2, or 3 gets the click event.
I read that changing the Z value of the GameObject's transform is one way to do this. Is this the recommended approach?
That doesn't seem to work though. Even setting the "wall" GameObject to Z = -1 makes it still get the OnMouseDown call instead of objects with a higher Z value in front of it
Ah, Z should be greater the further away it is, of course
How to freeze character in x axis?
Depends
You using a dynamic rigidbody?
i'm using rigidbody 2d
Is it dynamic? Are you moving it through velocity/forces?
Dynamic
I wish the character could still move around, but not to flip
You mean you want to freeze the rotation and not the position?
RaycastHit2D hit = Physics2D.CircleCast(groundCheck.position, radius, Vector2.down, 1f, 8);
This doesn't hit anything, even though it should. All the vars are valid
Your Layer Mask looks sus
Use
public LayerMask myMask;
Configure the Layers in the editor
And use that in your circle cast
If that's supposed to be layer 3 it's ok, if it's supposed to be layer 8 it's wrong
Use a LayerMask
Not string or Integer
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
public GameObject pauseMenu;
private void Start()
{
pauseMenu.SetActive (false);
}
public void TooglePauseMenu()
{
pauseMenu.SetActive(!pauseMenu.activeSelf);
}
public void ToMenu()
{
SceneManager.LoadScene("yee");
}
}
can someone tell me why its dosnt working? ps ignore the unknown script thats a other script.
I'm guessing you have 2 scripts named LevelManager
Or 2 scripts each containing a class named LevelManager
File name might not match it
Im almost certain my code is right to make a gameobject destroy itself when it enters a trigger but nothing is happening do objects need a rigid body or a collider to work with triggers?
- both objects need colliders
- at least one collider needs to be a trigger
- at least one object needs a Rigidbody (it can be kinematic)
@snow willow Thankyou! The problem was that I didnt have a rigidbody on either objects
Im trying to set a variable to a insantiated clones gameobject so that I can destroy one clone at a time and not the entire prefab and I am having trouble doing so.
I have tried putting the script on the prefab so that the instantiated objects might destroy themselves one at a time but its not working
The Instantiate function returns a reference to the instantiated clone
So you can capture the reference in a variable there.
Having the script destroy itself should work as well.
assuming you have a way to trigger said destruction
yeah just realised lol
um need help with shooting
Don't crosspost @maiden lance.
ok
hey all
weird noob question,
i have a sprite that's visible in my scene view, but not my game view?
it's on the same z layer as everything else - and i believe should be visible?
any idea where im going wrong?
(forgive me if this is the wrong place - i don't want to crosspost, so tell me and i'll move)
hey, I am trying to make a raycast to detect if my character is at a ledge so that it can grab on to it, I already mad the raycast, what I am having trouble with is selecting only certain colliders for the raycast to detect, so to only have the edge colliders be detected by the raycast and trigger the animation, so how do I do that?
code:
//get raycast origin position
shootRaycast = raycastOrigin.position;
//get raycast direction
raycastDirection = raycastOrigin.TransformDirection(Vector2.right);
//raycast
hangEdge = Physics2D.Raycast(shootRaycast, raycastDirection, 1f);
//visualize raycast
Debug.DrawRay(shootRaycast, raycastDirection);
(ah - figured it out, for some reason the parent had a -10z value)
oh yeah, thats because if you spawn a gameobject it will sometimes spawn it in random weird locations
so always when creating a game object, especially in 2d games first make the location 0,0,0
you can use the layer mask to ignore objects on a certain layer. i think that is the only way to ignore certain objects https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
oh thanks, Ill try that
guys how can i make one block impossible to pass?
Like how?
Hey, so I am using the unity IDragHandler stuff to make certain objects drag and droppable, however I also wanted to be able to rotate an object 90 degrees when the player right clicks, but unfortunately that just starts a new drag. How do I write my code so the player can modify the object while dragging?
Hi Guys, is this a good place to ask some simple questions regarding 2D stuff? I just started messing around with unity and have some questions for "setting up empty objects to be filled later" and getting components or parents of components 🙂
Yep you can ask questions here
Thats awesome! I'll try to figure out the stuff I dont get and all and write some questions later then 🙂 Thanks!
Ok i got one: How can I change the Color of a children 2D Object Sprite from a Parents Script?
I find a lot of stuff with
Color parentColor = this.GetComponentInParent<Renderer>().material.color;
GetComponent<Renderer>().material.color = parentColor;
and so on but whenever I try something with the GetComponent Stuff it always fails and throws errors like
Evaluate request failed (Could not resolve type: Renderer).
Evaluate request failed (Unknown member: GetComponentsInChildren).
and so on, depending on which angle I try to tackle the stuff 😄
Anyone know why I would get an error if I did public float mobStrMod = (mobStr + 10) / 2;
what is the error message
set the variable on Start
do what the error says. it says } expected so put it
You cant assign the variable based on another variable when you declare it like that
so how would I be able to do it 😮
Just declare it, and assign the value you want in Start like Hasan said
I swear I did that exact thing and it didn't work, but it is now XD thanks guys
It's not even doing the math -.-
Doesn't seem to be running the Variables at all
Is this supposed to update with whatever i declare these variables to be?
hey I need a short guidance. I want to draw a sprite, and some text, at the bottom left corner of the camera, and I want them to stay there even if the camera moves later on. How should I do that? thanks
If you know how to make the text just make ur a child to the player and camera a child to the player
It*
this is the tree so far, so what component should I create as a child of Battlefield?
@rare lake The initialization values are only used when the component is created, after that it uses the Unity serialized values.
could somebody help me please?
So I just do a void start() or something else for them?
No.
Set the values in inspector if you want to have default values. Set them in Start or wherever if you want to override the serialized value
Alright
If you set the value in Start I can't see what the benefit of making them serialized at all is
So what would be my best bet?
whatever makes sense for you
You can use [NonSerialized] attribute to disable Unity's serialization of that field
Or just make it private
Well I’m trying to make it so the stats are dependent on level, which will match the player level so that the game scales to the player
The relevant question is do you want to set values per instance in the inspector?
Or do you want to set them in code?
If it's the former, leave them public or private with [SerializeField]
If it's the latter, make them private or public with [NonSerialized]
How do I make them NonSerialized
private int mobLevel;
or
[NonSerialized]
public int mobLevel;
Oh so just make them private?
yes...
Oh 🥴
Wouldn’t that make it so I can’t use it in a separate code for like player or something
Then do:
[NonSerialized]
public int mobLevel;```
or, even better:
public int MobLevel { get; private set; }
Noice, thanks
Then I can just do Debug.Log(mobLevel); if I wanna make sure it went through in the console right?
of course
Alright, just wanted to make sure I had the code right for it
Tbh that top one with the brackets looks cleaner 😂
they do different things
What’s the difference?
the first one is just a public field with a special attribute on it to tell Unity not to serialize the field. The [Nonserialized] attribute is just a hint to Unity that says "don't serialize this"
The second one is a property. Properties allow you to carefully control access to variables in your script
^ Yeah by default unity automatically serializes public fields, so you have to tell it not to
Neat
Something I did was creat an empty, name it player, drag the camera to it to make it a child of “player” once you start putting in the stuff for the character and everything the camera will follow the players movements. When you make the text object, however you do that, do the same thing and drag and drag it into the “player”
thanks!
if I use
gameObject.transform.Translate(x, y, z);```
all of its children will be translated as well, if I understand you correctly
hello
So I am German and would have a problem with Unity because I want to make a start menu for my game, unfortunately I don't know my way around and so I watch videos and other things so that I can develop my game. Well that works quite well but my problem is that when I do this menu I have to create a new scene, but when I jump to the other scene the other one is simply deleted everything that was in there. I tested this before I do it on my real project but I don't know what to do next. Have you got an idea?
did you save the scenes ?
hello, it's me, for the 1637912748923178934 time!, i'm struggling a lot with this enemy AI stuff i try to implement, the problem is that the enemies yes, are targeting the player and instantiating bullets at the player BUT dont aim towards the player i guess the problem is in the way i stored the closestPlayer variable but im not sure
also, when a enemy shots, it transfers the player position to a vector2 called target but... is a completely mess!
code for the AI of the enemies: https://pastebin.com/mVMmWNS7
these ones are'nt as important or related as the one up but anyways i think it would be usefull
code for the behaviour of a normal bullets
https://pastebin.com/fa29EDg5
code for the behaviour of the other bullets
https://pastebin.com/sUmDHzpu
How can I create gameObject and move it to vector2?
Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
hey, Is there a way to check if there's a tile present on a tile grid or not?
like i have multiple tile objects considered as map layers as a child of grid so is there a way to check if tile is present on that grid?
I would guess it best done during collision detection else you're stuck with possibly searching the hierarchy for the unknown.
tilemap.hasTile
or
tilemap.getTile if you want a specific tilemap
remember to do using UnityEngine.Tilemaps;
yw
Good Morning,
Why would't an light source NOT cast shadows on an object while using the ShadowCast2D ?
I think I got it, I need to enable shadows on the lighting source ;P
how do i do ontriggerenter2d with a tilemap because when i have this it only counts the first tile i walk onto instead of all
sorry, can you please tell me how to also drop the code?
If not, I've created some numbers: can't I import them directly into Unity to create a font?
A font file is a bit different than just being an image
You can use your images as a Sprite or Image object, and combine them to make the illusion they're acting as a font, but not necessarily as a font without converting it
To be more precise, with the same font style, my white background is not there:
Oh gotcha. Your white is being imported as alpha somehow
They're exactly the same files as what you just posted above? The alpha seems correct on the numbers above
In fact, the numbers with the white background were created by me. Simply because in my game, with the font, there is no white inside the numbers
Wait I don't get you. The image files you uploaded above are the same as the ones you're using in your game, or they are not?
No, they are not the same. To put it simply:
-
In my game (without the white background) it's an installed font (.ttf)
-
The numbers with the white background, it's me who created it (.png)
I created these numbers to try to put them in the place of the font because currently, they don't have a white background, here it is
Ok understood, yeah you'll need to convert your images to a font, which isn't totally simple
Fonts don't really use pixels for things the way an image does
Because a font needs to be able to zoom up/down by a lot and stay crisp
So a font file is actually a description of the lines and paths that make up a "glyph", or character
There are tools to convert a .png to a .ttf that you can try
But because the formats are so different, pixels vs vectors, tools don't always do a good job converting
then, I don't know if there is another solution to have a font with a white background as I want, maybe with the Text Mesh Pro
You'll have to find a font that is designed the way you want, or you can modify the font in a program made for editing fonts like FontForge
FrontForge is free? ah I know otherwise. I also have this:
Know otherwise? Yeah it's free and open source
well, I thought of putting the font in white and adding a black outline but the outline is blurred, I had forgotten
In fontforge?
no in Unity
and you can add colour to font forge, can't you? so I edit my figure and add white to it
I didn’t see a UI channel so ima ask here, for EXP for example as a variable could I set up the UI to have a border than have the bars horizontal transform be linked to the EXP variable to “fill” if that makes sense
Oh shit lol thanks
I am trying to make my character in Unity 2D be able to hang onto an edge until I press a button and it will either climb up or fall down depending on what you press, but until you press something it just hangs there, and to make sure it doesnt fall down I made the gravityscale 0 and the velocity in both axis 0 as well, once you press W it will go back to normal and pull you up, but the problem is that it would make the velocity 0 and gravity scale 0 on each frame, I need it to happen only on the first frame that it detects that you are on a ledge (using a raycast), every frame after that it doesnt need to update it until I either press W or S feel free to ask any clarifying questions because I am not very good at explaining things
this is the first script(I wrote this in two scripts to keep it a bit more organized):
// name of the raycast
if (hangEdge)
{
if (Input.GetKey(KeyCode.W))
{
rb.gravityScale = 5;
transform.position = Vector3.Lerp(transform.position, myPosition[posIndex], lerpTime * Time.deltaTime);
t = Mathf.Lerp(t, 1f, lerpTime * Time.deltaTime);
if (t > 0.9f)
{
t = 0f;
posIndex++;
posIndex = (posIndex >= lengtht) ? 0 : posIndex;
}
}
}
second script:
if (hangEdge) {
//get rigidbody component(rb is the name of a rigidbody2D variable)
rb.GetComponent<Rigidbody2D>();
if (myFunctionCalled == false)
{
//change velocity on both x and y axis to 0(essentially tell player to stop moving)
rb.velocity = new Vector2(0, 0);
//set the gravity on this object(the player) to 0
rb.gravityScale = 0;
myFunctionCalled = true;
}
}
else
{
//set gravity on this object(the player) to 5
rb.gravityScale = 5;
}
I also made my own attempt at solving the problem, to no avail
pls ping me if you have an answer
also thanks in advance
@still tendon
You could freeze your rigidbody upon touching the ledge, and unfreeze when you get input
(rigidbody.constraints)
alright thanks, Ill try that
I checked aome tutorials on yt, as a beginner, I dont understand one simple thing, why do people use "vector3" in 2d games as opposed to "vector2"?
In example, transform object to x,y they used transform new vector 3 (xx,yy) id think ignoring z(2d), it would be overall better to use vector2?
Or did i simply misunderstood vector3/2 in general? (And the number is not related to dimensions)
I think it's because you can't assign a Vector2 to transform.position, but not too sure about that
There are 2 reasons. In some cases, the way you mentioned is correct. It's better to use a Vector2 if you really don't need the z value
But like wtch28 says, transform.position is actually a Vector3
Even in a 2d game, Unity does it in 3d but with the Z value fixed to 0
Ah, good, thanks :)
You can actually create different visual layers in a "2d" game this way, by moving them along the Z
On the same note, if im spawnong something on top of something else, that is in fixed position, is it better to use instantizate(or whatever its called) with vector xy values or with object to spawn o top of ? Not sure what the differences/advantages are
Example, i have a square in fixed position, and in script i wantt o spawn object on it, i can instanciate it using the circle, or, sinfe it is fixed, x,y vector on the circle, if that makes sense
If you use a Vector3, it goes to that position and is not a child of anything. If you use an object (transform) it will make it a child of that object
Is that so?
Thanks
So
Instanciate (go1, go2)
Makes go1 child of go2
Instanciate (go1, vector3)
Moves go1 to poaition of vector3
from what I learned, unity does gameobjects in 3d even if the game is in 2d, but if you have a 2d game it will do physics calculations in 2d
Correct. Keep in mind, being a child of an object means you're in the same position as it
So they both move it to the position
But one makes it a child
@left lotus thanks a lot, makes more sense now
It now makes sense why my object was rotated on wrong axis when i ritated my circle on x instrad of y, and when i scaled my circle the sprite scaled too
I fixed that by scaling the circle in prefab and then when i dragged my prefab to scene it was scale 1 1 1 again, so it worked, but ill try to refrain from doing it in the future, as it seems to add more work
hello, it's me, for the 1637912748923178934 time!, i'm struggling a lot with this enemy AI stuff i try to implement, the problem is that the enemies yes, are targeting the player and instantiating bullets at the player BUT dont aim towards the player i guess the problem is in the way i stored the closestPlayer variable but im not sure
also, when a enemy shots, it transfers the player position to a vector2 called target but... is a completely mess!
code for the AI of the enemies: https://pastebin.com/mVMmWNS7
these ones are'nt as important or related as the one up but anyways i think it would be usefull
code for the behaviour of a normal bullets
https://pastebin.com/fa29EDg5
code for the behaviour of the other bullets
https://pastebin.com/sUmDHzpu
How do I change the color of a 2D sprite in code so that I can enter a hexadecimal which determins the color
why my 2D lightining looks "inverted" on my game view and in the scene view it looks just as expected?
It Seems that something was wrong with my camera
Hey unity lovers! was hoping someone here might be able to suggest a decent tutorial for programmatic isometric tilemap generation, text or video doesn't matter I just can't seem to find much on the subject.
Any help is much appreciated!
Hi all -- relative noob to Unity here posting for first time. I'm working on an app that has
a static grid I want to display (the camera won't be moving around). I want it to look good on different devices, but I have an issue where due to the camera, some of the lines are distorted depending on the device viewing it. [here]: https://pasteboard.co/JWhZ1uE.png is the original image, [here]: https://pasteboard.co/JWi2jZm.png is an example where it is slightly distorted. Right now I'm not particularly worried about scaling properly, I am just trying to understand how to display an image without any distortion across devices (expecting that on a device with 2x the pixels vs another similar sized device, it'll be 1/2 the physical size). I am also curious if there are any really good tutorials out there dealing with 2d / pixel perfect rendering / UI elements. It looks like pixel perfect might do what I want, but in the little playing with it I've done, my UI elements are very distorted -- text just doesn't look good when I'm using pixel perfect.
Simple and lightning fast image sharing. Upload clipboard images with Copy & Paste and image files with Drag & Drop
Simple and lightning fast image sharing. Upload clipboard images with Copy & Paste and image files with Drag & Drop
Thanks much for any pointers 🙂
So I realized I posted a wall of text there. A simpler question that would help me greatly is just this: Is there a way to have a setup that will display an image on my target device pixel for pixel the way the image exists in the original file?
Have you tried Unity's pixel perfect camera package?
I've played with it a little bit, but haven't found any great tutorials for it either. If there is a good one you're aware of, I'd be happy to go through it.
I'll investigate it more, thanks 🙂
@west trellis No crossposting, please.
All I recall is Unity having a blog on how to set it up, but I've never used it myself. Have a look for that blog post.
cool will do thanks
Just in case you're not trying to be funny, I literally copied your question into Google and appended "unity" at the end of it.
So I have two triggers set up on an enemy and player game object. I am trying to make a simple system where the player can punch the enemy and knock them back a small distance and have the same happen in reverse. However, because of how triggers work when a punch occurs both triggers are activated on the players and script and the enemies script. This causes an unintended effect where the knockback is applied to both objects instead of just the one being punched. Is there anything I can do about this or I need to look at a different way of activating the knockback.
Has anybody seen ScreenPointToRay giving incorrect results when using a pixel perfect camera?
It works when game view is maximized, but not when just docked in an editor window.
hey, avery basic question: how do i ad an infinetly generating flat plane in 2D?
do you want to make it like a topdown plane or a platformer type plane?
Someone help me out im trynna make a platformer and i want the player to turn red when it touches a hazard and i cant figure out whats wrong here
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HazardReaction : MonoBehaviour
{
public SpriteRenderer playerRenderer;
private bool playerHit = new SpikeScript().playerHit;
void Update()
{
if (playerHit)
{
playerRenderer.color = new Color(255, 0, 0);
}
}
}```
the error code is
"You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor ()
SpikeScript:.ctor ()
HazardReaction:.ctor () (at Assets/Scripts/Player/HazardReaction.cs:8)"
the error message is clear
not much to add to that
@rotund burrow https://www.youtube.com/watch?v=-kd68uKt4jk
🐇 Save 50%-70% on the Unity Asset Store during the Spring Sale that begins on April 12! https://assetstore.unity.com/spring-sale?aid=1100l3e8M
This video will show you how to access variables from another script in Unity.
Download Project Search & Replace https://assetstore.unity.com/packages/tools/utilities/project-search-65234?aid=1100l3e8M&...
hello i made a script that makes the camera follow my sprite. It works correctly, but it doesnt display right
thats what the camera sees
public class CameraFollow : MonoBehaviour
{
public Transform player;
public Vector3 offset;
void Update()
{
transform.position = new Vector3(player.position.x + offset.x, player.position.y + offset.y + transform.position.z);
}
}```
nvm fixed it
with a simple move script probally
Does anyone know how to ignore physics2D collision between objects with the same tag?
I tried using the Physics2D.IgnoreCollision in a OnCollisionEnter2D but it doesnt seem to work
{
if (collision.collider.CompareTag("Spike"))
{
Physics2D.IgnoreCollision(collision.collider, GetComponent<Collider2D>());
}
} ```
This is the code im using
Basically im planning to make an enemy that'll shoot out spikes in a radial directions, and i want those spikes to not collide with each other once they are instantiated.
Nvm i got it working
hey, I created a BoxCollider2D through code:
gameObject.AddComponent<BoxCollider2D>();
BoxCollider2D boxCollider = gameObject.GetComponent<BoxCollider2D>();
boxCollider.size = new Vector2(cam.rect.width, cam.rect.height);
where cam is a Camera component. I made it have the same width and height as my camera. Now, how do I make it have the same center, since BoxCollider2D.center is deprecated?
anybody here know what the offset represents?
Offset would be the local space offset from the transform position
how can i disable the rigidbody2d and collider of an object in-code?
so the actual center would be ```cs
Vector3 centerInWorldSpace = transform.TransformPoint(boxCollider.offset);
Colliders can be directly enabled/disabledx with the enabled property
Rigidbdoy has to either be destroyed or set body type to kinematic
ok
thanks
oh one more thing
would setting the gravityScale of a rigidbody make it not affected by gravity at all?
If you set it to 0, then it will not be affected by the global gravity setting
ok thank
sorry, I'm still a beginner and I've been reading this over and over and I still don't understand why applying TransformPoint to the offset would give you the center (world) coordinates. I would have thought that it would give you the world coordinates of the gameobject + Vector2(offset.x, offset.y)
because the offset is a position in local space
TransformPoint converts a position in local space to a position in world space
that's all there is to it
yes, I agree with that, but:
that's not the local coordinates of the center, is it?
anyway - I think if you're just trying to align this collider to the camera, why deal with offset at all? Just let the offset stay at 0 and set the position of the collider x/y to the same as the camera
offset is the local coordinates of the center of the box. It's relative to the Transform's pivot location
wow, I had no idea. It's written nowhere, as far as I've searched. Thanks
so you mean, something like that:
gameObject.transform.SetPositionAndRotation(new Vector3(cam.transform.position.x, cam.transform.position.y, 0f), new Quaternion(0f, 0f, 0f, 0f));
where gameobject is the object having the boxcollided2d as a component
something like that but just set the position, no need to set rotation (btw new Quaternion(0, 0, 0, 0) is an invalid quaternion)
transform.position = new Vector3(cam.transform.position.x, cam.transform.position.y, 0f);
If you want to set rotation too it would be like:
transform.rotation = Quaternion.identity;
setPosition doesn't exist, and I've had errors with doing transform.position = , it was my understanding that I was changing a copy of transform.position rather than changing it directly
setting position changes it directly
the thing you had a problem with was probably something like:
transform.position.y = 5f;
^ that you cannot do
but you can set the whole Vector3 at once
no issue
ok thanks
long story short, the following:
gameObject.AddComponent<BoxCollider2D>();
BoxCollider2D boxCollider = gameObject.GetComponent<BoxCollider2D>();
boxCollider.size = new Vector2(cam.rect.width, cam.rect.height);
gameObject.transform.position = new Vector3(cam.transform.position.x, cam.transform.position.y, 0f);
will make a boxcollider exactly where the camera is, which will allow me to use OnMouseDrag for my script component
Hey, so i am a beginner and i am working on a small game project. I have a problem and i feel like i am missing a simple solution.
i have a player object and another gameobject.
when the player presses space the game object is destroyed and replaced with another object. the UI interface reflects an additional point for picking up the object. I would like it so that the player can only hold one object at a time.
right now my problem is that my player can continue to interact with the other objects even though it has one object counted already. i would like the player to be unable to interact with the other objects until it has removed that object from the count
my player has this code implemented
private Text bagCounter;
public int bagAmount;
private void Start()
{
bagAmount = 0;
}
void Update()
{
bagCounter.text = "BagCounter: " + bagAmount;
}
I cant seem to put all the code on here but you get the jist
zcoord0fMouse = Camera.main.WorldToScreenPoint(transform.position).z;
mouse_offset = transform.position - mouseWorldPos();
How can I remake this code in 2D?
I'm very confused by something and not sure how to go about explaining it
I'm trying to have my boss object create emitters that also fire bullets. The script that controls emitters and the script that controls the boss both inherit from the same script where this bit of code comes from which creates the emitters to start with. What happens is the emitter successfully retrieves all of these values except for the location and rotation. They emit bullets but they don't move when they're supposed to. What I found the reason to be is because the emission script finds instBulletEmitter (this variable was declared at the start of the parent script) to be null.
I had trouble destroying this object before I changed it to read GameObject.Destroy(gameObject)
which is where I later learned the script doesn't have a value for instBulletEmitter. I've created objects in this way using similar functions to the one above before so I'm not sure why it's acting up now. I should also mention that this was working before but I can't pinpoint when it stopped working so I'm not sure what I did to cause it to break.
I had suspicions it had something to do with being inherited but I'm not so sure. I'm all out of ideas
Debug.Log("OnPointerDown");
no work
Why is nothing displayed in the console?
Either you have logs disabled or that code is not running
but how to enable logs?
They're enabled by default but top right of console window are 3 small toggles
One for normal logs, one for warnings, one for errors
i am still a bit confused about when to use scriptable objects currently i have created instances of playable characters that all share the same set of abilities so i'm using the scriptables for that but i was also considering using scriptable objects for enemies that share the same code is that a good way to go? or should scriptables be more for inventries etc.. ?
and do i keep all the animations code within that or seperate that out?
I like to think of ScriptableObject as just like some static data holders that can be created, referenced, and modified from the Unity Editor.
You can use them for other stuff but that's the main way I use them
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=BGr-7GZJNXg
Let's make a very simple Drag and Drop in Unity, great for an Inventory System.
Simple Inventory System in Unity (Store, Use, Stack and Drop Items)
https://www.youtube.com/watch?v=2WnAOV7nHW0
If you have any questions post them in the comments and I'll...
did everything as per the lesson and nothing works and the game does not give errors
"nothing works" isn't a particularly useful hint
ok thanks @snow willow was just reading online another guy who only uses them for data not functions unless it's something trivial and have other scripts use the data is this what you would recommend?
Even the console in the unit does not work for me for some reason
public class DragObject : MonoBehaviour, IPointerDownHandler
{
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("OnPointerDown");
}
}
I created a script and added it to the object
i didnt think multiple inheritence was a thing in c#?
Yeah wouldn't recommend them for nontrivial behavior coding
It's not, that's an interface
ah 🙂
Do you have a Collider2D on the object?
An event system in the scene?
An inputModule?
A physicsRaycaster2D on the camera?
Not to rush or anything but is there any solution on my thing or do I need to provide more information?
hey guys... I got a GameObject whose OnMouseEnter gets called twice every time point on it... thing is it only has one collider... anyone encountered the same problem ?
Does it have any children with Colliders?
@snow willow just figured that shit out... I had a class which inherited from another one and I was calling Awake from the inherited class which somehow overrode the parent's class Awake where some important stuff was happening
You're calling something on line 20 of EnemyFollow which hasn't been assigned.
gotta be target is null
I've been following a code Monkey tutorial for a top down shooter and don't know what to do here, it just says there is no definition of it even though it's at the top
Remove the public object UtilClass ... line. The tutorial doesn't even mention that. Make sure you're following it correctly.
when i do that this happens
Then you're not following the tutorial, did you skip through some of the videos?
No
You're missing using CodeMonkey.Utils;.
Oh I didn’t see that, thank you
i need some help with my 2d platformer
i want it so when I hit W, my player goes through a door and goes to a different scene. but what if I want to go back?
for ex: player spawns at bed, he goes outside and back, after loading the scene he will always be at the bed
What's the question? What have you tried? What works? What doesn't? etc.
I solved it it was just that i forgot to check "Used By Composite" in the TilemapCollider
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelManager : MonoBehaviour
{
public GameObject pauseMenu;
private void Start()
{
pauseMenu.SetActive (false);
}
public void TooglePauseMenu()
{
pauseMenu.SetActive(!pauseMenu.activeSelf);
}
public void ToMenu()
{
SceneManager.LoadScene ("MainMenu");
}
}
Does anyone know how I can set a 2 second delay when I instantiate my items? Like wait 2 seconds and then the items spawn
Why doesnt this flip the player ? When he goes left he should face left but he doesnt
Nvm i fixed it
im experiencing something very odd
im making a chess engine and to generate the board and pieces i use a few loops
i use one big loop for every chessboard cell with a big switch statement that determines which piece should go where
however, it seems as if unity gives up the loop about halfway through and just restarts the entire function, resulting in an infinite loop
what the hell could be going on
i probably messed up somehow but i dont see why it would do the entire Start function again lol
im so confused, it stops halfway through my loop and then the start function starts again
Seeing code would likely allow others to better help you diagnose the situation.
alright but it's quite a lot and im not sure if people are willing to take the time to through it all and understand it
so i'll ask something different i suppose
how can i check if my scene is somehow being restarted? (causing my function to be abruptly halted and causing the start function to keep looping)
like the only reason the Start function would get called again is if the scene somehow reset
Add a Debug.log that only sends a message in the first frame, and if it sends more then once then the scene or code is restarting somehow
can somebody help me
public class RocketControl : MonoBehaviour
{
public Transform player;
public float angle;
Vector2 CurrentDirection;
public Rigidbody2D Rigidbody;
public bool EngineRunning = false;
public float EngineThrust = 0f;
private float EngineMaxThrust = 100.0f;
public float EngineThrustPrc = 0f;
void Start()
{
Rigidbody = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
angle = player.rotation.x+90;
CurrentDirection = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
CurrentDirection.Normalize();
if (EngineRunning)
{
Rigidbody.AddForce(CurrentDirection * EngineThrust);
}
}
}```
i am making a rocket simulator
and this happes with this code:
if i dont add 90 to the angle, this happens:
good idea, thanks
Did you save? Physics should be handled in FixedUpdate. Are there missing code you are not showing us?
oh
player.rotation isn't Euler and likely not what you're thinking.
the same still happens
So are you not showing us code or is this the complete class?
What're you doing with angle? (Implies you may be doing other stuff you aren't informing us of)
this is literally the entire class
and for some reason the thrust is being applied in a constant direction, no matter the rotation
Well angle isn't what you think it is.
So the direction is completely off.
Rotation is a Quaternion not Euler
angle = player.rotation.x+90; would give you some unknown result.
It has x, y, z and w components but they are not Euler values.
Rotation is a Quaternion: https://docs.unity3d.com/ScriptReference/Transform-rotation.html
man
For simplicity first use a static direction of Vector2.up
yeah but the whole point of this is to apply the thrust im poining in
public class RocketControl : MonoBehaviour
{
public Transform player;
public float angle;
Vector2 CurrentDirection;
public Rigidbody2D Rigidbody;
public bool EngineRunning = false;
public float EngineThrust = 0f;
private float EngineMaxThrust = 100.0f;
public float EngineThrustPrc = 0f;
void Start()
{
Rigidbody = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
}
void FixedUpdate()
{
if (EngineRunning)
{
Rigidbody.AddForce(Vector2.up * EngineThrust);
}
}
}
That float value angle isn't what you think it is.
You likely want it's Euler representation.
yes
so Transform.EulerAngles.z?
Assuming you're referring to the instance of Transform (transform) it would be transform.eulerAngles.
aand it still does weird things
What's the current code?
With simply Rigidbody.AddForce(Vector2.up * EngineThrust); does it do the proper action?
with Rigidbody does it use internal coordinates or global?
They're using forces and not setting position directly; physics.
void Update()
{
angle = player.rotation.eulerAngles.z+90;
CurrentDirection = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
CurrentDirection.Normalize();
}```
thats the current main method
not sending anything else bc it has not changed
Alright I've got to go but just lastly want to mention that mathf cosine is expecting a value in randians
Whereas I believe you're assuming it's in degrees.
There should be conversion in the mathf utilities https://docs.unity3d.com/ScriptReference/Mathf.html
k added angle = angle * Mathf.Deg2Rad;
And you would then apply the direction to force rather than vector2 up
I've got to go, good luck.
I really need help on this, I can't do a whole lot to proceed until I know how to sort this problem
@wintry sonnet Don't crosspost.
How can I duplicate the CreatorKit:RPG fading sprite effect in other projects?
Guys, please tell me a script that will move the decor like in Sims 2d
Rigidbody2D rb;
AudioSource audioSrc;
bool isMoving;
[SerializeField]
List<AudioClip> clip;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
audioSrc = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (rb.velocity.x != 0)
{
isMoving = true;
}
else
isMoving = false;
if (isMoving)
{
StartCoroutine(Walk());
}
else
StopCoroutine(Walk());
}
IEnumerator Walk()
{
int index = Random.Range(0, 3);
audioSrc.PlayOneShot(clip[1]);
StopCoroutine(Walk());
yield return new WaitForSeconds(0.5f);
}
need help
my sound is happening constantly
You are suffering from a misunderstanding of the workings of coroutines
in more ways than one
Coroutine walkingCoroutine;
// Update is called once per frame
void Update()
{
if (rb.velocity.x != 0)
{
isMoving = true;
}
else
isMoving = false;
if (isMoving)
{
if (walkingCoroutine == null)
{
walkingCoroutine = StartCoroutine(Walk());
}
}
else if (walkingCoroutine != null)
{
StopCoroutine(walkingCoroutine);
walkingCoroutine = null;
}
}
IEnumerator Walk()
{
while (true) {
int index = Random.Range(0, 3);
audioSrc.PlayOneShot(clip[1]);
yield return new WaitForSeconds(0.5f);
}
}``` @still tendon
np
Hey, I also have a small question.
In the Screenshot you see two 2D collider.
The big one is to track if the player is close to the enemy...
But the Problem is:
That a bullet that I made, dedects the big collider as an hitbox... so its to easy to hit the enemys...
How can I say the Bullet, that only the small collider is the right?
PS: Sorry for my bad english
I'm also sorry if this is the wrong channel
@gleaming moss in the unity menu, go to edit > project settings > physics 2d. At the bottom there is a section, "Layer Collision Matrix". You can set up different layers and say whether they interact with each other or not. Then put the large collider on a gameobject that has a layer that doesn't interact with the bullet
@fickle prairie Thank you very much, I like people like you, who help others for free!
Does the rpg tutorial code in communityinfo still work? I tried inputting the code, but it says there's a compiler error
I'm trying to get a picture of my code, but discord isn't opening on my computer
Youre missing a semicolon. You need to connect your visual studio to Unity as well.
How do I do that?
Instructions are pinned in #💻┃code-beginner
And where? Lol
Your script is short, figure it out.
I appreciate it, thank you very much!
21?
add a semicolon to line 21
hey, how would i write a code to rotate a sprite on the Z axis after i press a key?
how to make a 2d triangle sprite in unity 2020?
Hi I am a bit confused about 2D triggers and colliders. I have script on two objects that should write a message in console, but only one does. Any chance anyone can explain it to me?
