#๐ผ๏ธโ2d-tools
1 messages ยท Page 22 of 1
ok
@thick geyser Do the things you are trying to hit have actual colliders?
can use Debug.DrawRay/Line to visualize the raycast
always do ^ when raycasts aren't working as intended
oh ok, do i just copy the raycast part into that?
look up the documentation on how those work (: Similar to raycast overloads, but not exactly the same
do this line below your raycast
Debug.DrawLine(transform.position, transform.position + new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")), Color.red);
I see, let me try that
Just to see if it is the right direction
im assuming interactableDistance is not 0?
A better way of doing it would be
Vector2 dirOffset = new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")) * interactableDistance;
Debug.DrawLine(transform.position, transform.position + dirOffset, Color.red);
.normalized
His raycast isn't normalized
so this would be more accurate
Unless the raycast auto normalizes
nah it doesn't
not actually sure about that
oop need to change the vector 2 to a vector 3
just cast the transform.position to a vector2
(Vector2)transform.position
that doesnt work
be more specific
it cannot be used like a method
you have a typo somewhere
post code
read what I sent again
new Vector2
and wrong encapsulation
try to think why you are writing something before actually typing it. () basically encloses the values inside it into a single expression. so everything inside () is a single value
Unity dropped the native support for that
I remember reading somewhere you gotta do that on your own, they have an example somewhere
so we cant do that anymore?
there is no ray being drawn, hmm
yeah
then are you sure interactableDistance isn't 0
try increasing it
alright
to like 5
hundred
what is the radius of your character?
because anything under the radius as the distance value makes no sense
what do you mean by radius? the size of the sprite?
if your player collider has a .5f radius or something
then .2f as the interact distance will never exit your player collider
oh I see whats happening, it is too small
^ the maxDistance is from the centre of the player position.
it needs to be at least larger than the radius of your player
I guess i may have to make it scale for the up facing then
my game is a top down rpg, for context
that isn't context
that's what I thought, why would it need to scale up though?
oh wait, the ray is coming out of the head and not the collider at the feet
screenshots ๐คทโโ๏ธ
i mean is screen configuration like this
oh alright
I forget exactly what it is called, but there is some property in there to get the offset
@pulsar barn Yeah, dont think that exists anymore in newer versions
you have to make an options menu instead
Yeah you need to make your own in the settings of your game
i hope unity creator make setting like that again
hmm, I disabled the button input for testing.
the line is touching, but it isnt detecting
I may just be an idiot and missed something obvious though
@plush coyote
It might be detecting your players collider
You can use a layer mask to only detect the other object, or get an array of all collisions and loop through them
ok, I tried doing if (interactable.collider != playerObject.GetComponent<Collider2D>())
but that didnt work
ill try the layer mask then
the second parameter of the raycast is not your destination of the cast
it is just a direction
You can put in some more debugs to see if it's detecting any collisions
@thick geyser You should pass in a direction as the second parameter
oh yup that makes sense
if you want to be consistent, change your dirOffset line to this
Vector2 rayDir = new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")).normalized;
and pass rayDir in as the second parameter of the raycast
then, add back your interactableDistance as the third parameter
for the debug line, change it from using just the transform.position + rayDir to transform.position + (rayDir * interactableDistance)
already did that while you were typing lol
remember to normalize it
where do I normalize?
if you want to be consistent, change your dirOffset line to this
Vector2 dirOffset = new Vector2(anim.GetFloat("horizontalMoveLast"), anim.GetFloat("verticalMoveLast")).normalized;
ok, there
now let me try this out
hmm, still nothing. I need to set up a layer mask I guess
Send your current code
but yeah, you should use raycasts regardless
how about you debug.log in the outer if statement
to see if it hit anything
So then your interactable doesn't have the tag you think it has
Either it has no tag, or one is misspelled
or it is hitting something else entirely
Then I would set up the layermask
in both places
ok
thank you for all your help btw!
I know ive probably been a pain lol
not really, a lot of people here just ask for free code and copy paste without understanding anything
you actually understand whats going on though, so its easier to help
yeah, I dont like doing that. I have been dealing with this problem for 2 days, trying to fix it myself. Thats what I really want is to understand it for later
ok, I just had to set the player's layer to Ignore Raycast
Its working now!
it would be better to pass in a layermask as a parameter of the raycast
and have the interactables on a specific interactable layer
then you don't even need a tag for them
because your raycast would only be able to hit interactables
thats true, then I could make NPCs also on that layer
yeah
Im also planning on putting trigger colliders in front of each object or on the side I want a specific interaction for. Does that make sense in conjunction with the raycast?
I want that so I can also put things in corners and not worry about overlapping
what do you mean in conjunction with
like, the raycast would hit the trigger?
or the trigger would work independently
the trigger would be independent
so I could have the player have a different response interacting with the back or side of something
I cant really say if it would be better or not because I don't know how everything in your project is set up
yeah that makes sense, ill just have to see as I go
but you can always just ask here again if you have a specific issue with it
yeah, thanks! you've really helped me, and I've learned some good things to make my code better too!
see you around then when I break something again haha
Hello there, currently I;m having a project that uses LWRP(I know, it's an old one), I am having some issue when introducing pixel perfect camera into the project
The game was designed at 960x540 on 16PPU
so I set up the project that way
However after I switch the screen resolution into 1080p, or 4K, even if I've checked the stretch fill
The rendered image remains un-scaled
Never mind, just found it, I have to use 2D Renderer in order to make that actually works
Hi everyone, soo my buddy created this youtube channel ( reallly stupid and funny contant ) and he has 57 subs. today is his birthday and i would be so happy if we can get him to 100 subs โค๏ธ thank uvery much to everone here. have a good day โค๏ธ https://www.youtube.com/channel/UCJkZVFN4sgZPePMW6WwTXZA
Guys I have one question
To designing of an object which software should I use for 2d
pixel art or?
ANY
@tidal marlin I have mainly used Pyxel Edit and Aseprite, and so far I prefer Pyxel Edit mainly since I work with tiles a lot. I like the features it comes with for auto drawing on all tiles and so on.
And it's only like 9 bucks.
Could someone pls send me reference script of saving data for the player or any kind of data save?(to save progress and option settings)
hi guys, anyone knows whats a better way to create a game manager
as singleton or builder pattern?
Unity 2D Collider, is there a version of OnTriggerExit but it triggers when only part of the collider is exiting
I need this cause I have a terrain (e.g. water) and I only want to make water sounds while the player is on top of it, this works when the player "enters", but when it exits, there's some delay because the player's collider is "bigger" and not a single dot, so that causes latency before the water walking sound changes back to the normal walking sound, if that makes sense
the only workaround is i have to create colliders surrounding the water as well, for the hard concrete floor
You could use OnTriggerStay and compare bounds yourself
true ty
im trying to make my character move left and right but it says it has erros, does anyone know what those might be?
Me too buddy
@sharp storm It should tell you what errors it has :p
You could use OnTriggerStay and compare bounds yourself
@spring ledge its harder than i thought (to make the footstep sounds in/out of the 2D terrain sound nice/responsive). I think the next solution I thought of is to make a "tiny" collider 1x1 pixel wide, store it as a child gameobject of the player, and when the player is moving right, it'll move this collider to the right, if left, then left, if up, then up, if that makes sense.
ah i can use OnTriggerStay and the direction
i'll try ontriggerstay with direction into account
i mean it does, i just dont understand what it means 
@sharp storm Well, step one would be to tell people here what it is
Crystal balls are rare these days
Not a string, but there is a = where it shouldn't be. Double click the error, and check the code (or post it here).
you lack an opening { i nline 14
Also that if in line 26 needs another closing ) and probably and opening { after the closing) in the next line :p
i am pretty new to unity and i am making a platformer and i need help getting a mario-like variable jumping system
ie you jump higher the longer you hold the button
maybe u could use rigidbody2d and check if the jump button is pressed and apply an upward force for every time they hold the button until its high enough
ie you jump higher the longer you hold the button
@fervent ermine reduce the effect of gravity while the velocity is positive y and the jump is held
anyone using 9 slice in unity?
@sharp storm in your screenshot, your IF statements and your FixedUpdate functions, you're missing the { and your If statements are missing their closing bracket, they should look like this:
im trying to make my character move left and right but it says it has erros, does anyone know what those might be?
@sharp storm Friend
First question here.
Using boxcast for isGrounded, issue is that when jumping from under a platform I get grounded because of the collider, I've tried to make the boxcast smaller heightwise but to no avail.
Is it a good practice to make a empty child and have the boxcast on that instead?
Or should I disable the platforms as I am jumping (not falling) ?
Any tips would be great, ty
might be wrong channel, sorry if so
I've seen multiple tutorial use an empty gameobject to place the boxcast, don't see why you wouldn't. You could even just add some offset to your transform.position, but it's nicer to be able to place it in the editor
I wonder what the best way for a groundcheck is though. I've often seen the boxcast way, but it's kinda weird imo. You already have a physics engine which stops your object, so it feels like you should be able to use that
Ok yeah, that is sort of what I want to be able to do, not fiddle with gizmo or debug.draw
Maybe can just set it on OnCollisionEnter or so
Would have to check orientation and such though, since else you'd still set ti to true if you hit your head on a platform instead of your feet
I've tried so many approaches and always found issues I could not fix ๐ Boxcast is what I've been looking for, cept for the platform thing atm. :)
I will try the empty and if it fails I will fix with OnCollisionEnter, I have time ๐
Thanks for the input!
tbh, I wish I could like
[SerializeField]
private GameObject groundCheck;
private void Start(){
groundCheck.GetComponent<Collider>().OnTriggerEnter += (col) => {
//code
}
}
setting the OnTriggerEnter of an object the script is not attached to
That would've been ace
but there is a way to get another object is there not? ๐ค I am quite the noob at this so not sure
u can get another object with, like GameObject.Find, or some RaycastHit but
i only know how to set the OnTriggerEnter/OnCollisionEnter of the object a script is currently attached to
OnTriggerEnter isn't a real even,t it's just a function called by Unity
Ok yea
I can prolly implement my own way of doing it
Thank you so much for helping guys
Hey I'm creating a Tower Defense game and now that I have a wave system with enemies prefabs I want to start placing towers. So for this I have to define where can the player place a tower/turret. I currently have a Grid that contains Tilemaps (Road, Decorations, Buildable terrain...)
Since this is a grid and I can actually see the cells in my Scene view would there be a way to do something with my BuildableTerrain Tilemap? Like getting every cells in this Tilemap or something?
I mean, you have errors. Check your code in the editor and see what's wrong. If you "don't understand any of it", you probably will have to learn C#
it says various things
do i change it?
it's text
u just replace the text as u would in a word document
basically,
ok, but i want u to
click moveSpeed
then hold alt and press the down arrow key
once
if u are using Visual Studio
Teaching them fancy shortcuts
that should move that line down
now save the file
and see if it works in Unity
I have a feeling "horizontal" is supposed to be "Horizontal"
that's what that axis is called by default
of course, it's possible for people to change input settings
cant watch streams rn
Well once you remove all the errors, it should work. Does it stil show errors?
You still ahve to move the moveSpeed line
yea it needs to be under the {
then remember to press ctrl + S
to save ur file
that asterik at the upper left means ur file is unsaved
like anyone who doesn't follow my religion
You need to move line 6 down the "public float movespeed"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2d : MonoBehaviour
{
public float moveSpeed = 5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 movement = new Vector3(Input.GetAxis("horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
}
this should work
notice this:
{
public float moveSpeed = 5f;
Once you attach this to your object, and you press play
if your character does not move whenever you press your left and right arrow keys
you might need to change this line
Vector3 movement = new Vector3(Input.GetAxis("horizontal"), 0f, 0f);
to
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
Anyone knows how I could have a turret system for my Tower Defence game? I already have a Grid that contains Tilemaps (one for the road, one for the buildable area...) but the only thing I can get so far is all the cells position within a tilemap but it also takes the empty ones any idea if there's a way to check if a tilemap cell is "empty" or another way to do this?
@still tendon you defined your condition in the Jump method. You're calling Jump() every time and checking if you're jumping that's kinda weird.
You should rather put your condition
if (Input.GetButtonDown("Jump")
where you actually call Jump (in your Update() I guess) and call Jump() inside it.
Then define Jump() to do a single action (just like what you'd expect from something that says Jump) as follow
void Jump()
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(, 0f, 5f,) ForceMode20.Impulse);
}```
@still tendon you didn't understand my point you should ask question if you're not sure you understood what I explained.
In your Update() put this
if (Input.GetButtonDown("Jump")
{
Jump()
}```
and define your Jump method like this
```csharp
void Jump()
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
}
if you read the code above it makes sense because in your Update() which is literaly "Update every frame and see if something changed in the code" you call IF I press Jump button THEN you jump
you don't need to check if you're jumping when jumping this doesn't make any sense, do you understand my point?
Think of it as if you code for someone who don't know anything about computers
if I press Key.JumpKey then Jump() nothing more
make it english
like even if the person knows nothing she should still understand
void Update()
{
if (Input.GetButtonDown("Jump")
{
Jump()
}
}
void Jump()
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
}
@still tendon but you have to understand why I did it like this
did you understand? I can't make it simpler
which part don't you understand?
a method is defined like this:
access modifier (public or private) which you don't have here
void | return types (what your method will return, void is to create a method that just executes stuff without giving back data somewhere else in the code)
Jump is the method name, how you call it
@still tendon
If you're new to C#
it's a good idea to learn how to make console applications first
yeah
This shows how to create a new console app in Visual Studio 2019
Once you know how to do that
I recommend watching something like Brackey's series on C#
He's using Visual Studio Code rather than Visual Studio 2019, but it's ok.
Same language.
The reason for learning how to code via console apps is because they are lighter.
There are less distractions.
I use console apps whenever I just want to test some C# code
When you use Unity, it's expected that you know every topic in that list
But, of course, you could learn while using Unity if u want
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour{
public flow movementSpeed;
public Rigidbody2D rb;
float mx;
private void update() {
mx = Input.GetAxis("Horizontal");
}
private void FixedUpdate() {
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
rb.velocity = movement;
}
}
doesnt show movement speed?
public flow movementSpeed; is that supposed to be 'float'? :p
I don't see anything in the code that should cause issues. However, Unity doesn't update those if there's any errors (including in other scripts). So check the console for those, if any.
I mean, it's still called PlayerMovement there, have you renamed the script as well as change dthe class name in the script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMover : MonoBehaviour{
public float movementSpeed;
public Rigidbody2D rb;
float mx;
private void update() {
mx = Input.GetAxis("Horizontal");
}
private void FixedUpdate() {
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
rb.velocity = movement;
}
}
yes
And that file is PlayerMover.cs?
yes
And you're sure Player Mover is what you have attached there, and not PlayerMovement?
Also, any remaining errors in the console?
Yeah, so remove that and re-attachit
remove what
the component thats the PlayerMovement script from your object
Also you probably don't want private for Update/FixedUpdate, and Update instead of update
ok back
Run, Player, Run! We look at creating a player movement script for a 2D Platformer in Unity. This is the second part of our 2D Platformer in Unity series.
Thanks for watching!
Twitter: https://twitter.com/tyler_potts_
Go check out my main channel: https://youtube.com/c/tyler...
7:06
im following the tutorial
Well remove the PlayerMovement thing from your object and drag PlayerMover into it
Click on player and screenshot the inspector
Yes, drag your rigidbody to the Rigidbody slot on PlayerMovement
kk
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMover : MonoBehaviour{
public float movementSpeed;
public Rigidbody2D rb;
public float jumpForce = 20f;
public Transform feet;
public LayerMask = groundLayers
float mx;
private void Update() {
mx = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded ()) {
Jump();
}
}
private void FixedUpdate() {
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
rb.velocity = movement;
}
void Jump() {
Vector2 movement = new Vector2(rb.velocity.x, jumpForce);
rb.velocity = movement;
}
public bool IsGrounded () {
Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);
if (groundCheck.gameObject != null){
return true;
}
return false;
}
}
@still tendon you dont have a variable name on line 11...
why do my objects i put inside player keep disappearing
?
You're making them while the game is running
click it
probably groundCheck is null
Hey I have a problem with the 2D TileMap Extras, it doesnt show me prefab brush anywhere
@still tendon ". Null is returned if there are no colliders in the circle."
Then he did it wrong
@still tendon do you mean mine?
Does anyone have an Idea where I can find it?
Thx
But they arent my assets
All I did was the shadow lol
you check if groundCheck is null
oof but its a good game ur working on though
That checks if groundCheck.gameObject is null, yes
And if groundCheck itself is null it'll error
๐
so how would i fix
check if groundCheck isn't null
What did you try
by deleting return false;
So
I told you to check if groundCheck isn't null
How do you arrive at deleting return false; to accomplish that
You don't
so do i just delete the null
as I said, you're checking if groundCheck.gameObject is null, aka, the if gameObject field of the class that groundCheck is (in this case Collider2D) is null
so in that you're checking if groundCheck.gameObject isn't null
now how do you check if groundCheck isn't null?
hm
i think i may know
let me see
actually
idk
public bool IsGrounded () {
if Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers) != null);
if (groundCheck.gameObject != null) {
return true;
}
return false;
}
}
i tried that
well it wont work
you have an if there, how do you modify that to check for groundCheck instead of groundCheck.gameObject
remove game.object?
Yeah
So what code do you ahve now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMover : MonoBehaviour{
public float movementSpeed;
public Rigidbody2D rb;
public float jumpForce = 20f;
public Transform feet;
public LayerMask groundLayers;
float mx;
private void Update() {
mx = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded ()) {
Jump();
}
}
private void FixedUpdate() {
Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);
rb.velocity = movement;
}
void Jump() {
Vector2 movement = new Vector2(rb.velocity.x, jumpForce);
rb.velocity = movement;
}
public bool IsGrounded () {
Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers) != null);
if (groundCheck != null) {
return true;
}
return false;
}
}
Well you have to remove that != null) thing again you put in there
after the Collider2D groundCheck = [....] stuff
I find a lot of these tutorials that don't seem to explain the coding stuff much kinda weird I guess
Makes it seem like people just think of it like some weird incantation
no errors but it doesnt jump ;/
In Update() put a Debug.Log(IsGrounded()); and check what it outputs in the console while you're running the game
ok
It outputs whatever IsGrounded() returns to the console
Hmm show your game as thats printing out
Whats feet, and whats groundLayers set to too
Also whats with the mouse gestures ๐
and if you click player?
click the feet thing again and press ... W I think it was
should have a gizmo to move that around
What would be a good / clever way to make a character "skin" selection?
?
Not that far really
I was thinking about just changing the position of a sprite to fit the character but I'm sure they're would be a smarter way.
Just a bit , and not to the side ๐
Still a bit too far downjust a tiny bit lower than it was before
Then click on Player and show the PlayerMovement thing in the inspector
Yeah, sorta like that should work
It's just since the radius for it is .5 and your player is 1. So a .5 radius might not find the ground because it ends right as your player ends, doesn't intersect with the ground. So by moving it down slightly thats better
No, like, the script hitng
Where you set feet and groundLayers an dsuch
That seems right. Click ground and make sure it's on the Ground layer
YE
but
i need to make proper characters now
because with a blob if the feet are on one side and it flips then i cant jump
Can I have the same line of code in two different pages? I need to trigger an animation when I am grounded but my isGrounded is on another page.
GetComponent<otherScriptName>().isGrounded
GetComponent can access other scripts attached to your object
Thank you
@tropic inlet I am getting the following error from what you told me to do "Assets\Scripts\PlayerController.cs(26,40): error CS0122: 'Controller.m_Grounded' is inaccessible due to its protection level" Any ideas?
There should be a public property like isGrounded or something
if not, you could always go into the code and change m_Grounded to public
Works perfect, thanks
Anyone know how to fix this, the problem is the collision is not working. Like the debug.Log statements does not show in console and the hitpoints variable doesn't go down when collision is made. And yes my enemy object has a box collider.
I'm trying to make a simple project where the ball bounces and when it hits a wall the background color changes
I have the ball bouncing off the walls I just dont know how to add the collision to change the background color
This is where I am at
I tried adding GetComponent<Renderer>().material.SetColor("_Color", Color.red); when the ball collides with the walls, but all it does is change the ball color and not the background
You should configure VS so you get autocomplete and error checking https://docs.microsoft.com/en-us/visualstudio/cross-platform/getting-started-with-visual-studio-tools-for-unity?view=vs-2019#configure-unity-for-use-with-visual-studio
You should configure VS so you get autocomplete and error checking https://docs.microsoft.com/en-us/visualstudio/cross-platform/getting-started-with-visual-studio-tools-for-unity
@hollow crown it's visual studio @upper wedge is using
That is visual studio?
They need to properly configure it
It should not say Miscellaneous Files
I'm making a knockback mechanic for a game which knocks back the player based on its x position relative to the enemy, if the player is to the left of the enemy the knockback direction will be left and vice versa. To check this I am transform.position.x for both characters. The issue with this is that their original value is not the same. The original x position for an enemy could be -20 for the player. How do I solve this?
if you take both of the game objects and put their x position at 0, they won't end up at the same position in the scene
damn
if gameobjects have the same location, they should be at the same spot as far as I know
could it be that
ur colliders are positioned incorrectly?
like
maybe the collider is distant from ur gameobject's center due to some offset
their origin points aren't at the same location
according to the inspector for these two game objects, their position on the x axis are both at 0
the distance between them isn't 0 which is what causes the issue with the knockbacks
How did you manage that ๐ค
They're like 7 units apart horizontally despite both being at 0?
I suppose their position might be relative to where they were placed
shouldn't be
Do they have a parent that moves?
Then 0 would be relative to parent
At least in the editor
That might be it, they donโt have the same parent
Wheres is the parent at?
And how do you calculate the knockback
transform.position.x should give you world coordinates, not relative to parent
The editor shows relative to parent though when you have it selected
Can someone help me getting every non empty tile in a tilemap (and only in the tilemap) please?
Getting every green cells only (Tilemap Collider 2D) would be cool
I'm trying to check if a tile is part of a tilemap and if it's not empty when I click on it.
Basically what I want is to have a buildable tilemap and build something whenever you click in any of the tiles in this particular tilemap. I tried lot of different stuff but I really can't get anything good
That sounds like a terrible way to do that ๐
You should somehow get mouse position and calculate the tile clicked from that
Then you can access that specific tile directly
Instead o fhaving to build a gigantic list
Well yeah I'm really lost here I've been searching since yesterday.
For now I have the mouse position when clicking and I can check if the click position is within the tilemap
but it's an area so it also takes other tilemaps and all
Well I'm not sure if your setup is
if (Input.GetMouseButtonDown(0))
{
Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pz.z = 0;
Vector3Int cellPosition = myTilemap.WorldToCell(pz)
foreach (var VARIABLE2 in myTilemap.cellBounds.allPositionsWithin)
{
if (cellPosition == VARIABLE2)
{
transform.position = myTilemap.GetCellCenterWorld(cellPosition);
}
}
}

for now cellPosition is my mouse click position converted to the tilemap
then I check if my click is within the tilemap bounds (foreach) and if click position == a cell within the bounds I set my tower here
the thing is that the foreach is really bad
Well good that you realize that it's bad
the mouse click only works in my buildable tilemap but as you can see here if I put a block bottom right I can build everywhere between
presumably you want to use https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.HasTile.html with that position you get from WorldToCell
What do you mean with "build everywhere between"
it seems to be working.. I can't be believe it's that simple
I found this before but got caught in so much things that I forgot about this method
yeah sorry what I meant is moving. whenever I click on one of the tile in the tilemap it moves the GameObject the script is attached to$
well thank you very much I was searching since yesterday morning I feel so dumb
can't believe I got stuck so long just for this but again thanks a lot!
I have a question, i am making a 2D game, but when i move the object and there are colliders on both objects and in the code if i just have void OnTriggerEnter2D it wont work. Can you help me with this?
this is the exact code private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("colided with lava");
Destroy(collision.gameObject);
}
private means it can't be accessed from beyond the definition of the class
For functions like Update and Start, I just make them private because there is no reason for any other script to access it
@clever sky Public fields will be displayed in the editor and can be edited (like this)
Thats the way i can explain it
public fields*
same thing
functions are a bit different
yes i know
public functions will be visible to the animation event thing
But wouldn't OnCollisionEnter2D() need to be a public method?
nope.
welp
@brisk hemlock how "Doesn't it work"?
u can mix them @ Timi
you can reserve cinematic ones for, like, special enemies or
highly skill-based tactics employed by the player
depends on the mood of ur game and how frequently they happen, rly
also how long they take
hey i have issues with getting my character go of the map when I jump, i have created a ontheground variable ans I putted this line of code in the void updat thing if (Input.GetKeyDown("space") &&ontheground) I don't understand please help
hi
i need help
how would i move 2d sprite in upward direction according to the sprite using rigidbody2d
@silent bay do you remember to update ontheground?
I don't understand you question maybe
ok let me put everything
Are you trying to make a jump function
no
no
Are you trying to make a jump function
@clever sky
I want to make a function that makes my player not fly around with spamming space
oh
oh
i want the 2d sprite to go to upward direction with respect to its rotation
any help
``
in that case
wtf it's getting delelted
@silent bay use hatebin or something
You can't post a whole files content into a text message here
ok lol
@silent bay make it so you do like
if (Input.GetKeyDown("space") &&ontheground)
{
ontheground = false;
// rest of the code here
}
i want the 2d sprite to go to upward direction with respect to its rotation
any help
@fiery oar anybody knows how
I just did it
...just rotate the game object? @fiery oar
what do you mean with respect to it's rotation?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class charactercontroller : MonoBehaviour
{
public Rigidbody2D rb;
public float vitesse;
public float sautmax;
private bool ontheground = false;
void Start()
{
rb.velocity += new Vector2(vitesse, 0);
}
void Update()
{
if (Input.GetKeyDown("space") &&ontheground){
Jump();
}
}
void OncollisionEnter2D(Collision2D col)
{
if (col.gameObject.CompareTag("ground"))
{
ontheground = true;
}
}
void OncollisionExite2D(Collision2D col)
{
if (col.gameObject.CompareTag("ground"))
{
ontheground = false;
}
}
void Jump()
{
rb.velocity += new Vector2(0, sautmax);
}
private string GetDebuggerDisplay()
{
return ToString();
}
}
that's my code
Meaning they want it to go "up" on the local up direction, not the global up direction
Presumably
what do you mean with respect to it's rotation?
@grand cove i want it like in 3d we use transform.forward so like that how to use it in 2d
Meaning they want it to go "up" on the local up direction, not the global up direction
@spring ledge yeh but how to do
what if you fix this OncollisionExite2D to OncollisionExit2D?
@fiery oar What does transform.forward give you?
(there's an extra e in your version)
@fiery oar What does transform.forward give you?
@spring ledge its for vector3 so it wont work
i want it for vector2
@fiery oar What does it give you? Abstractly, not the value
nope
@fiery oar Btw, 2d games still use vector3 for gameobjects
you can just convert the vector 3 to a vector 2...
but i've tryed with and without and the probleme is &&ontheground
you can just convert the vector 3 to a vector 2...
@grand cove how to convert it
just put (Vector2) in front of the vector 3 value
is there a other function maybe?
vector 2 is literally the same thing as a vector 3 but it has 1 less value <.<;
@silent bay try and Debug.Log("Jumped") in you collision code to check if it even gets called?
void Update()
{
if (Input.GetKey("left"))
{
if (Input.GetKey("right"))
{
shipRB.velocity = new Vector2();
Debug.Log("working");
}
}
}
its my update loop can you tell how to do
oh goodness, you need to learn how to code c# before starting to make a game, bruh
ok
oh goodness, you need to learn how to code c# before starting to make a game, bruh
@grand cove but whats wrong in these code
why would you press both left and right at the same time?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class charactercontroller : MonoBehaviour
{
public Rigidbody2D rb;
public float vitesse;
public float sautmax;
private bool ontheground = false;
void Start()
{
rb.velocity += new Vector2(vitesse, 0);
}
void Update()
{
if (Input.GetKeyDown("space") &&ontheground){
Jump();
}
}
void OncollisionEnter2D(Collision2D col)
{
if (col.gameObject.CompareTag("ground"))
{
ontheground = true;
}
}
void OncollisionExit2D(Collision2D col)
{
if (col.gameObject.CompareTag("ground"))
{
ontheground = false;
Debug.Log("Jumped!!")
}
}
void Jump()
{
rb.velocity += new Vector2(0, sautmax);
}
private string GetDebuggerDisplay()
{
return ToString();
}
}
i want the game to be like when i press left it rotates left and when i press right it rotates right and when i press both at the same time it goes in upward direction
thks man
then you can at least see if it stops colliding with the ground
i want the game to be like when i press left it rotates left and when i press right it rotates right and when i press both at the same time it goes in upward direction
@fiery oar i want it to be like the minecraft boat controls
any help
i want the game to be like when i press left it rotates left and when i press right it rotates right and when i press both at the same time it goes in upward direction
@fiery oar something like
if(Input.GetKey("left") && Input.GetKey("right"))
{
// code for moving forward
} else if (Input.GetKey("right")) {
// code for rating
} else if (Input.GetKey("left")) {
// code for rating the other direction
}
Or are you asking for the code for moving "forward"?
yeah but instead i want to go upwards
bro
fixit ๐
void Update()
{
if (Input.GetKey("left"))
{
if (Input.GetKey("right"))
{
shipRB.velocity = new Vector2(what to write here);
Debug.Log("working");
}
}
}
I rarely code in languages with semicolons
shipRB.velocity = transform.up; @fiery oar
Hi! I was trying to get a Text (TextMeshPro) show up for a few seconds in my scene as soon as I touch it's collider. However, it doesn't seem to be working, can I get some help?Thanks in advance
but 2D is different from 3D, there is not forward @fiery oar you have to calculate that your self or rotate the game object and keep using transform.up as "forward"
it works
i want no gravity in rigidbody2d so it moves in the direction for ever
how can i make it to come at rest in the script
public class Ship_Controller : MonoBehaviour
{
public Rigidbody2D shipRB;
public float speed = 1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("left"))
{
if (Input.GetKey("right"))
{
shipRB.velocity = transform.up * speed;
Debug.Log("working");
}
}
}
}
its my whole script
I believe you can remove gravity from the inspector
@clever sky so i fixed it but it doesn't fucking work
How do i add gravity and movement to my game
This is literally stuff you learn from basic tutorials @fiery oar
https://learn.unity.com/search?k=["tag%3A58088f5f0909150077ca2bc6"]
@clever sky so i fixed it but it doesn't fucking work
@silent bay but does it print?
so I think i'm just gonna rewrite everything
i know
Thats why I asked you what forward returns btw
heu
as z axis is towards the screen
How do i add gravity and movement to my game
then the collision doesn't exit
Forward returns the positive Z-axis. What has 2D? x, and y. So we do'nt need forward. Whats up in 2d? y. Whats the transform for up?
i have my issue fixed
@spring ledge isn't it just .up?
yes
do you think the problem is from "collision2D"
How do i add gravity and movement to my game
@still tendon Read up on rigid body and use the unity beginner tutorials.
The collision doesn't trigger
oh
I personally don't know how to trigger collision, I just know how to print statements my way to victory ๐
gonna check
From the code pasted earlier, it was OncollisionEnter2D
public class Ship_Controller : MonoBehaviour
{
public Rigidbody2D shipRB;
public float speed = 1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("left"))
{
if (Input.GetKey("right"))
{
shipRB.velocity = transform.up * speed;
Debug.Log("working");
}
}
}
}
here i want my gravity to be off in the inspector by doing so the object continues to travel in the direction forever so how to gradually decrease the velocity
public class Ship_Controller : MonoBehaviour { public Rigidbody2D shipRB; public float speed = 1; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetKey("left")) { if (Input.GetKey("right")) { shipRB.velocity = transform.up * speed; Debug.Log("working"); } } } }here i want my gravity to be off in the inspector by doing so the object continues to travel in the direction forever so how to gradually decrease the velocity
or the second way to say is how to implement gravity in code
Christ, people don't even do basic tutorials before they start blasting questions here any more, I'm off.
@spring ledge does gameobjects just casually have collisions for free? ๐ฎ
Only if you put in colliders?
That makes sense
Christ, people don't even do basic tutorials before they start blasting questions here any more, I'm off.
@grand cove i have basic knowledge but i want the efficient code that's why im asking
my issue solved
You're literally asking how to dampen velocity over time. I'm not sure that counts as basic knowledge ๐
If you know the basics, then you should know what transform does and how to use it to "fake" gravity.
So I made a platform collider so that you could go through a ceiling and floor, but if you go through the floor, it does not stop. I want to turn it off right after they go through it.
Any help?
@still tendon if I understand what you say you could use the OnTriggerEnter2D method (requires a Rigibody and a Collider 2D on your player)
then you could use the collider that's given in parameters and use .Compare("yourPlayerTag") as a condition and inside this if put your .enable = false or something
On what event would I make it false though @scarlet fractal
whatever you're using to make your collision turn it off
okay thanks
Do you mean Mathf.Abs(Input.GetAxis("Horizontal"))? Because Mathf.Abs("Horizontal") literally just gives it the string "Horizontal" when it wants a float
Is there a way to select all **particles **in a certain radius? The same way as OverlapCircleAll finds all colliders.
ans:
var droplets = new ParticleSystem.Particle[rain.particleCount];
var num = rain.GetParticles(droplets);
for (var i=0; i<num; i++)
{
if (Vector2.Distance(droplets[i].position, rb.position + rb.centerOfMass) <= radius)
{
droplets[i].remainingLifetime = 0;
}
}
rain.SetParticles(droplets, num);
@tame lava Use DistanceSquared and square your radius before comparing it
(Sort of depends on how many particles you have and how often you do that for it to matter though :P)
how would i go about designing a collision system for a grid ship like this https://gyazo.com/168659d73d306c6706b08963f242b998 ?
i thought about having the parent having a rigidbody and a composite collider, but i don't know how i would go about checking collision for individual blocks (as they can be damaged individually)
@spring ledge about 300 particles, every frame. Is DistanceSquared faster or something?
Oh, makes sense, it just doesn't need to take a square root every time.
Yeah
Idk if it's me being dumb but it
Cannot resolve symbol 'DistanceSquared'
var distSquared = Vector2.DistanceSquared(droplets[i].position, rb.position + rb.centerOfMass);
Vector2.cs doesn't have it.
๐ค
@tame lava Not sure why they don't have that, but you can do distSquared = (droplets[i].position - (rb.position + rb.centerOfMass)).sqrMagnitude instead
Oddly the sqrMagnitude docs even note that its faster than magnitude, and Distance says it's the same as (a-b).magnitude. So no clue why they decided to have no DistanceSquared
Hey I have a turret GameObject with this script attached that strikes every 2s and slows every enemy GameObject within its radius (Tower Defense game). My only issue is that when an enemy exits the slow radius his speed goes back to normal but almost of the enemies have their speed reduce once after it.
Anyone knows what I could do? Or at least see my OverlapCircleAll in my Scene to see if it match my turret Circle Collider 2D?
public class TurretTest : MonoBehaviour
{
void Start()
{
StartCoroutine(SlowAttack());
}
IEnumerator SlowAttack()
{
yield return new WaitForSeconds(2);
Collider2D [] colliders = Physics2D.OverlapCircleAll(transform.position, 7f);
if(colliders.Length > 0)
{
foreach (var VARIABLE in colliders)
{
if (VARIABLE.CompareTag("Enemy"))
{
Debug.Log(VARIABLE.name);
SlowEnemy(VARIABLE);
}
}
}
StartCoroutine(SlowAttack());
}
private void OnTriggerExit2D(Collider2D other)
{
Debug.Log(other.name + "EXITED RADIUS");
var script = other.GetComponent<EnemyMovement>();
script.Speed = script._defaultSpeed;
}
void SlowEnemy(Collider2D other)
{
var script = other.GetComponent<EnemyMovement>();
if (script.Speed > 2)
{
script.Speed = script.Speed - 0.5f;
}
}
}```
@spring ledge thanks!
@scarlet fractal Thats an odd way to use coroutines? why not just while true it
@scarlet fractal Also not sure what you mean. Enemies stay slowed?
@scarlet fractal that system is gonna break once you have more then 1 slow effect, because the Turret removes all slows and not just it's own. I would apply slows as a Debuff, but that would be a little to advanced for you I think.
someone wanna created a game 2D
True
@heavy token yeah you're right didn't think of this, I think I'm gonna search for a debuff tutorial then.
Maybe I could update an isSlowed bool on my enemy so that when it's false my enemy starts recovering his speed bit by bit instead of resetting to the default value so that if he enters in another slow turret's radius it goes back to isSlowed?
@spring ledge wdym while? I used OnTriggerStay2D() before but it ran my slow code every time.
IEnumerator SlowAttack()
{
while (true) {
yield return new WaitForSeconds(2);
Collider2D [] colliders = Physics2D.OverlapCircleAll(transform.position, 7f);
if(colliders.Length > 0)
{
foreach (var VARIABLE in colliders)
{
if (VARIABLE.CompareTag("Enemy"))
{
Debug.Log(VARIABLE.name);
SlowEnemy(VARIABLE);
}
}
}
}
}```
I don't really understand how this will change? Actually my slow is executed 1 more time than it should so would while(true) change this/what would it change?
It just mean you're not constantly making a new coroutine if you can keep one running ๐
so this will only slow my enemy once? what I want is a turret that hit the ground and slow enemies in its radius a bit every time it hits the ground while they're in the turret's radius
maybe I could also change the behavior to make just slow every enemy inside it to a fixed value and then whenever they get out they progressively get their speed back
@scarlet fractal he means that instead of calling your Coroutine again at the end of your Coroutine you could have it in an endless loop instead.
oh that's just better in term of memory usage? @spring ledge I'm not thinking of performance for now but thanks this should be way better performance wise
@scarlet fractal a debuff class would have a baseDuration, timer and enemy it is affecting. If it's a slow debuff it would have a slowAmount value, when it is applied reduce the speed of the enemy by X amount. When the duration reaches 0 add X to the enemies speed again.
But you would also have to learn about Inheritance
So like if the enemy is in the radius he will be slowed by 5 for 3 seconds but only once if he's already slowed
and when isSlowed is false he progressively gains his speed back
uh hi i need help in unity2d.
so i need to my player rotate towards nearest enemy, and i dont know how...
can anyone help?
@still tendon
Vector2 dir = target.position - rb.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg + 90f;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
```here's what i use for 2d rotations
Quick dummy question. Haven't worked in 2d in a while. I know in the past re-using animations with different sprites wasn't possible. Or at least not simple. But a while ago I saw a few presentations about sprite libraries that suggested they might be able to accomplish it. Am I on the right track?
haven't looked into sprite libraries but i haven't had any problems with these https://docs.unity3d.com/Manual/AnimatorOverrideController.html
Thanks, I'll give this a look and see how it goes
2D render pipeline with the new experimental 2d lights. Is it possible to get the value of illumination of an object somehow? Or better yet. Add a component to the light that can check if the player is hit by the light.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Scripts : MonoBehaviour
{
public float MovementSpeed = 1;
public float JumpForce = 1;
private Rigidbody2D _rigidbody;
void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
if (Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001)
{
_rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
}
}
}
Any help?
@still tendon you should learn C# before Unity. NullReference means the reference you gave is null which means nothing. In your error it's written Scripts.Update() so this happens in your Update() method. The problem probably comes from _rigidbody. Did you add a Rigidbody in your inspector?
Also you can debug yourself: is this problem happening on start or when I press the Jump key? If it happens when you press your Jump key then the problem comes from something inside your Jump key condition.
An f there doesn't matter though ๐ค
But the null reference exception definitely does ๐
Guessing you do not have a Rigidbody2D attached to your GameObject..
"it worked" isn't relative to the error you posted..
fmatters on assignment. For example float abc = 0.3; this would need the f. Because without any addition that 0.3 is a double, not a float. You're assigning it to a float, so you'd potentially get wrong data as a float is less precise than a double. Thats why it needs you to denote that you're putting a float by adding f. Comparing double to float works without f's
Why would you argue, when it works lmao
You sure you didn't assign a rigidbody during those tests or something ๐
Lets do it the science way
remove the f again
Does it break?
Yes
Because we aren't.. we're explaining your error.. not feeding self justifications ๐คทโโ๏ธ
Unlikely, but sure
Well.. I see the null reference exception error and.. "Any help'.. so not sure what you're asking if not for explanation support because it's a pretty simple error..
{
cout << "Didn't ask";
//end of chit-chat
}
Same but whatever ๐คทโโ๏ธ
Also you should use std::cout; there. using namespace std; is incredibly bad practice
๐
Couldn't care less, using namespace std; is way faster
and much more efficient
๐
That's what I told him
using std::cout;
For beginners, using namespace std; is fine. If they don't even understand what a variable, function or scope is, it's unlikely that they are writing any large projects that are vulnerable to name clashes.
When they start becoming intermediate, and they start writing larger programs, they'll begin to see the benefits of being explicit due to how the creators of the standard library dumped so much into one namespace.
Couldn't care less,
You are the first person in ages
that has used this phrase correctly
Everyone else says "I could care less", which is the opposite of what they intended to convey
I guess Norwegian schools are pretty good then.
hello, could someone help me?
I am producing a project where I need to throw objects and after a while they self-destruct, but all very quickly, since I send teleport. I can normally destroy the first prefab that the player shoots, but the next one is intact, being deleted only from the list and not being destroyed, I have been trying to solve this problem for a long time and I am new to programming.
My attempt:
{
yield return new WaitForSeconds(timerRange);
rb2b.constraints = RigidbodyConstraints2D.FreezePosition;
yield return new WaitForSeconds(timerRange);
Destroy(playerController.projectiles[playerController.projectiles.Count - 1]);
playerController.projectiles.RemoveAt(playerController.projectiles.Count - 1);
}```
I can't use "Destroy (gameObject);" since he gives the following error and I need the player to teleport as soon as possible: "The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object."
Sorry for my bad English, I'm not very fluent.
Anybody got tips for optimizing performance with large destructible physics enabled tilemaps?
GetComponent<Rigidbody2D>().AddForce(Vector2.up * 100.0f);
jump script done
i accept paypal
do normal charactercontrollers work on sprites?
u can create a gameobject, give it a sprite render and a character controller
Please Help! I'm trying to make a camera like Forager. I've been reading documentation and I am still confused.
{
viewPortSize = (cam.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)) - cam.ScreenToWorldPoint(Vector2.zero)) * viewPortFactor;
distance = player.position - transform.position;
if (Mathf.Abs(distance.x) > viewPortSize.x / 2)
{
targetPosition.x - player.position.x - (viewPortSize.x / 2 * Mathf.Sign(distance.x));
}
if (Mathf.Abs(distance.y) > viewPortSize.y / 2)
{
targetPosition.y - player.position.y - (viewPortSize.y / 2 * Mathf.Sign(distance.y));
}
transform.position = Vector3.SmoothDamp(transform.position, targetPosition - new Vector3(0, 0, 10), ref currentVelocity, followDuration, maximumFollowSpeed);
}```
**targetPosition.x - player.position.x - (viewPortSize.x / 2 * Mathf.Sign(distance.x));** and
**targetPosition.y - player.position.y - (viewPortSize.y / 2 * Mathf.Sign(distance.y));** have red squiggly lines under it. I am using code from 2019, could it be outdated?
EDIT: Nevermind, the "-" right after **targetPosition.x** and **targetPosition.y**, was supposed to be an equals 
Guys anyone know of a tutorial about GetComponent for Tilemaps?
I've found the reference.
Is there a way to assign a script to a tile or tile map. Should you create a likewise grid of tiles by returning TileMap.cellBounds and simulating properties?
Wait, if I create a huge array using TileMap properties from the TileMap I can calculate the exits from each tile
Then pathfinding is easy.
How can i get all objects in a spectify radius of a object?
Circle cast or sphere cast if your objects have colliders.
Circle cast or sphere cast if your objects have colliders.
@vocal condor thx, but i've already figured it out myself
how can i create a object by c# script?
You can create using instantiate or keyword new.
new GameObject?
i have a problem, why i have this All compiler errors have to be fixed before you can enter playmode! UnityEditor.SceneView:ShowCompileErrorNotification()
think
Fix them from top to bottom..
how can i give this gameobject a texture by script?
.... You need to start searching for tutorials online...
ok .-.
These are pretty basic questions..
A renderer allows an object to be displayed.
There are many types.
They are all components.
what am i supposed to do with the code from the link you sent me i don't understand
It wasn't for you.. you need to fix your errors.
Fix them from top to bottom..
@vocal condor
Scroll up and read the first error. I'm assuming you kept trying to play the application and unintentionally hid the original error.
i have nothing
I see six errors being reported.
look nothing
Double click and check the details pane below.
Clear the console as well.
Is this a new project?
nop i crated 2 week ago
Not entirely sure, it's not a script error (especially related to 2D), more like a setup error. Post your question in #๐ปโunity-talk.. Not much folks will be able to give you the exact answer but there are others on the net with your problem and the solutions aren't too solid..
ok think
@jagged belfry @jagged belfry @jagged belfry is a good programmer ๐
@jagged belfry yo bro
@jagged belfry Do you watch any anime
๐น
Not related to coding <@&502884371011731486> @still tendon
!warn @still tendon Don't spam ping people.
Pixie Sprite#7791 has been warned.
!mute @still tendon 1440
Pixie Sprite#7791 was muted
Thanks @vocal condor !
Does anyone know how to make 2d ragdoll physics for a stickman?
I just started Unity like this week and I want to make a 2d ragdoll game so i would appreciate any help
How can I make the object go in the direction he is facing?
@remote moth I think you could use Quartenion. Maybe try to Debug.Log Quartenion.Identity to see where he's facing
Hey I currently have a script that spawns a GameObject where I click but I can spawn an infinite amount of this GameObject on top of each other, is there a way to check if there's already a GameObject at my mouse position? I don't think creating a List of every GameObject I spawned would be a good practice performance wise.
Hey I currently have a script that spawns a GameObject where I click but I can spawn an infinite amount of this GameObject on top of each other, is there a way to check if there's already a GameObject at my mouse position? I don't think creating a List of every GameObject I spawned would be a good practice performance wise.
@scarlet fractal you want that it create one object wenn you click?
You could raycast to the mouse or something simple like that
No I already have this. My issue is that I only want to create one per position I don't want to have GameObjects on top of each other
If it is a grid based game, having a 2D array of your map would be a good option
If you actually want an object to take up one grid position, then yeah, have a 2D array of your map
When you spawn the object, you can round the position to the nearest grid position and set that position to "taken" or whatever
my only condition for now is
if (buildableTilemap.HasTile(mousePosition)```
then just don't instantiate something if the rounded position is taken
ok I'll try this thank you
he should go not completly in the correct direction .-.
Rotate to the object:
Quaternion GetRotationToTarget(Transform target,Transform i)
{
Vector3 targ = target.transform.position;
targ.z = 0f;
Vector3 objectPos = i.position;
targ.x = targ.x - objectPos.x;
targ.y = targ.y - objectPos.y;
float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;
return Quaternion.Euler(new Vector3(0, 0, angle));
}
Move in this direction:
transform.Translate((transform.up / 2) * 1);
that's a lot of code to get the direction to the target
Quaternion GetRotationToTarget(Transform target,Transform i)
{
Vector2 dirToTarget = (target.position - i.position).normalized;
float angle = Mathf.Atan2(dirToTarget.y, dirToTarget.x) * Mathf.Rad2Deg;
return Quaternion.Euler(new Vector3(0, 0, angle));
}
he got still in the wrong direction
But, you just want it to go towards the target?
But, you just want it to go towards the target?
@plush coyote yes
Vector2 dirToTarget = (target.position - transform.position).normalized;
transform.right = dirToTarget;
transform.Translate(transform.right * 5f * Time.deltaTime); // 5f is just some arbitrary movement speed number
that's the whole code
No need for quaternions or angles
and can i do that he rotate in the direction?
this code also does rotation
this code also does rotation
@plush coyote ok, thx
Use it all the time for my 2D projects
but yeah, it doesn't really make sense that it sets it
or at least, you wouldn't think it would
given the rest of unity's properties
he don't move correctly by me, i want to set once the direction
No clue what you mean by that
by creating the object
I mean, it can't change transform.right without changing rotation and such to match, I just expected it to be a read-only thing
thats what I meant ^ @spring ledge
given the rest of unity's properties, you would think its read only
No clue what you mean by that
@plush coyote i mean that
Whats that
Two black squares
@plush coyote since I have a GameObject manager I just added my GameObject position to a List of positions whenever it's instantiated. Does the job for now I might create a class with different methods later
nice
i mean that
he does not hit the object, but passes it
through it maybe?
next to it probably, since through it would be collisions
What passes what ๐
he move in the direction of the blue arrow, but he should in the direction of the red arrow go
and are these objects children of any other object
@plush coyote he has not childrens
create projectile
void SpawnProjectile(Collider2D[] enemys)
{
GameObject a = Instantiate(shootPrefab) as GameObject;
a.transform.position = new Vector2(self.position.x, self.position.y);
for(int i = 0;i < 100; i++)
{
Vector2 dirToTarget = (GetNearst(enemys).position - a.transform.position).normalized;
a.transform.right = dirToTarget;
}
}
Why is this looping 100 times
becaus the old rotation variant
@remote moth but wenn i do execute it once for a object has he not rotate
well, what is the code on the projectile?
That doesn't make sense, the loop doesn't do anything
well, what is the code on the projectile?
void Update()
{
if((self.position.x < -15f)||(self.position.x > 15f)||(self.position.y > 8f)||(self.position.y < -8f))
{
Destroy(this.gameObject);
}
transform.Translate(transform.right * 5f * Time.deltaTime);
}
when he is right to him, then the projetile move correctly, but...
..but, when he is over, under or left of him the, he move not so as he should
mean you this?
No
why does it have gravity
No
@spring ledge what then?
is that the projectile?
the actual object in the scene
why does it have gravity
no, i have gravity set to 0
Ah ok
A screenshot of that
@spring ledge of the scene?
Of the projectile selected in the scene
Discord dropping everyone's messages
after you press W
when i presswdo it nothing
hmm should work then
Getting nearest enemy method has to be wrong. Everything else seems fine
hmm should work then
nope
Getting nearest enemy method has to be wrong. Everything else seems fine
why is this method wrong?
Transform GetNearst(Collider2D[] Enemys)
{
Transform Nearest = null;
float distance = 1000f;
foreach (Collider2D x in Enemys)
{
float x_distance;
float y_distance;
Transform obj = x.transform;
if(obj.position.x > self.position.x)
{ x_distance = obj.position.x - transform.position.x;}
else{ x_distance = self.position.x - obj.position.x;}
if (obj.position.y > self.position.y)
{ y_distance = obj.position.y - transform.position.y; }
else { y_distance = self.position.y - obj.position.y; }
float NewDistance = y_distance + x_distance;
if(NewDistance < distance)
{
distance = NewDistance;
Nearest = obj;
}
}
return Nearest.transform;
}
Thats an odd way to get distance
Thats an odd way to get distance
yes, this my way to get the distance xD
Trying to think if that even works
yes this work
No, it does not
why not?
i have try it, this method work
Yeah, his old rotation method was like that too
tons of manual calculations that could have been done in 1 line
Say one object is at 0,0, the other at 9,1, so it's 9 tiles away from the first object. but you'd calculate that as 9-0, 1-0, then 9+1 = 10
Another object is at 5,6, so closer. But 5-0 = 5, 6-0 = 6 -> 5+6 = 11. So according to that it would be further away
literally
float distance = Vector2.Distance(obj.position, self.position);
if it feels like you are reinventing the wheel, you are probably doing something wrong (or there is a much easier way of doing it)
tons of manual calculations that could have been done in 1 line
this is, because that i unity yet not long using
but you could always google "get distance in Unity"
i have it so do, how i do it in python previously