#🖼️┃2d-tools
1 messages · Page 27 of 1
add a tilemap collider
is that a component?
yes
alright thanks
i will try
it worked
thank you so much!! ive been stuck on that for a while @distant pecan thank youuu
also if you start getting stuck on the ground, all you need to do is add a composite collider to merge tiles colliders
how can I SetCursor when I hover over specific region of the sprite? I thought of creating another invisible sprite and placing on top of it, but perhaps there is more efficient way?
How can i change the size of unity 2d tilemap colider since they are a bit to small so my character hits the bump between them? Ping me with the answer please
any recommendation on existing pattern / package for using vector art in UI?
This jump script is confusing me
it says that it coliding with its self
and even tho i made it were it can only jump on a layer mask "Platforms" it will just keep leting me jump "Fly".
Anyone?
whats the best way to get tile collision in tilemap?
like collided with tile of player
@trim jay check your mask, make sure your player isn't in a layer included there
The player's layer is default
Can someone help me out to find out why my code doesnt seem to work for my player movement
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
public float movementSpeed;
public Rigidbody2D rb;
float mx;
public float jumpForce=20f;
public Transform feet;
public LayerMask groundLayers;
private void Update()
{
mx=Input.GetAxisRaw("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!=null)
{
return true;
}
return false;
}
}
Don't cross post and why is jump being implemented in Update rather than Fixed Update?
thank you so much I didnt catch where the jump was being implemented
Why my Camera don't see my rectangle ?
your rectangle need to be an Image and not Sprite Renderer if you want to be UI
Ty
Lerp returns a value between A and B based on the 0->1 t value you pass in
you're passing an extremely small value in
so you will get back pretty much A
Where do you call the function?
Lerp1 need to be run every frame, not on click
Color origin = new Color(1, 0, 0);
Color destination = new Color(1, 0, 0);
float elapsedTime = 0;
while(elapsedTime < duration) {
currentColor = Color.Lerp(origin, destination, elapsedTime / duration);
elapsedTime += Time.deltaTime;
yield return null;
}
currentColor = destination;```
example in a Coroutine
There we go
The "pass Time.deltaTime * speed" model of using Lerp would need to be called continuously and A should be the current colour, not the origin colour
but it doesn't guarantee a timeframe, it just moves the current closer to the destination every call
different origin and destination? I'm not sure what you mean
Just flip start and target color
I am fairly new and it is say that the end } is "Unexpected" can i get some help.
Heyo, I'm trying to optimize my level thumbnail generation, currently I load the level and render it to a rendertexture (optionally saving it to a jpeg), then discard the level that I just loaded. However this is quite slow (a level consists of tens or hundreds of tiles) so instantiating all those is slow. What I'd like to try is to manually render the level to a texture myself without having to instantiate all these objects. I'm thinking of using Graphics.Blit or Graphics.CopyTexture, however these do not provide any rotation so I'd have to think of something for the rotation of tiles. Anyone here have any pointers on how to achieve this?
Quaternion.Slerp interpolates between two Quaternions, clearly
i didnt understood
https://docs.unity3d.com/ScriptReference/Quaternion.Slerp.html
public static Quaternion Slerp(Quaternion a, Quaternion b, float t);
you are passing Vector3s to it
You could use https://docs.unity3d.com/ScriptReference/Quaternion.Euler.html to convert them, or use Vector3.Lerp
depending on the application
oh
i didnt know vector3.lerp existed
ill try it
@hollow crown there is no quaternions at rot
Quaternions are a complex number representation of a rotation
you can't just take 3 of their values and construct a Vector3
if you want to use Vector3s you probably want .eulerAngles
like Vector3.eulerAngles or transform.rotation.x.eulerAngles?
transform.eulerAngles
im not atually trying to do that know
im gonna add it later
for now i wanna make the camera smoothly slide into player
Oh didnt realize there was 2d code
https://hastebin.com/wokuyozoyo.cpp
Having an issue were the bullt only goes in one direction rather then the direction the player is facing
Any help would be much appreciated !!
if i were to make a script where i would want my player to go a certain direction until it hits something, how would i make it
why not make movement scripts then add box colliders to the player and the object you want it to stop at?
what
I want it to go a certain direction even though you are pressing diffrent buttons
oh i see
so kinda like apply force from one direction until it hits a trigger ( like a spot on the map or a tree ) then it stops?
thats a good question lol
lmow
@slow egret
Vector3 rot = transform.rotation.eulerAngles;
rot.y = p.transform.rotation.eulerAngles.y;
Vector3 pos = p.transform.position;
pos.z = transform.position.z;
transform.rotation.eulerAngles = rot;
transform.position = pos;
does this work?
@tropic inlet This should work even if it does nothing yet, right. Just copying the same thing twice in rot.y and pos.z
So I would like to create a game like My Friend Pedro (I just begun with unity). I know this is a big project and I want to take it in small steps, like learning how to make the animations, graphics, shooting physics, body physics, blood physics, how to make good lighting, sprites, all that. Can anyone give me any adivce on what to start with and for any tutorials?
Brackeys on Youtube has a ton of great content, including some great 2D sprite and lighting tutorials. Code Monkey has a lot of really good C# tutorials for Unity
Follow along with tutorials while you prototype things, then refactor what works later for the final game
HI I have a question, I just watched a video from Unity and wanted to know where i get the level Generator Script? (https://www.youtube.com/watch?v=mFIAGVydVu4)
Learn more and try the preview build: https://ole.unity.com/newprefabs
Improved workflow
The new Prefab workflows, which are now available as previews, allow you to split up scenes and Prefabs on a granular level. This gives you greater flexibility, increases your productivity and enables you to work confidently without worrying about making t...
The description of that video has a download link for a preview build which probably includes the generator script
I downloaded it but I don't have any Scipts can you download it for me and send it to me please?
It is very important to me @thorn swallow
Sorry, I'm unable to download it right now, but if it's not part of the download then I don't know
ok
I'm trying to make a 2d camera system similar to that of Smash's - basically a camera follows all players, but it is confined to a certain area. I'm using cinemachine, and I have virtual camera that follows a targetgroup made of all players. Similarly, I have a cinemachine confiner that confines the screen edges to the correct bounds. This looks good for the most part, but I want for the cinemachine confider to override all else - there's certain player orientations where the camera is forced to go outside of the confider, but I want to force the camera to always stay inside of the confider no matter what. Any ideas on what I can change to acheive this?
If anyone is having an issue with building a mobile game, and then it slowing down/freezing after a few minutes, well, I have found the solution after days of researching. Message me if you are having the same problem and I can give you a few pointers on how to optimize your mobile game in ways that aren't really fully explained in documentation or forums.
@wraith root I personally haven't messed around with cinemachine very much. You could use a Vector3.Distance check between the camera and some points on the confider.
right, but you still can't limit the position of the camera - I'm thinking there's got to be a built in way somehow
just use a script with Mathf.Clamp
I've tried that before but cinemachine just overrided my clamp - I'll try again
parhaps LateUpdate @wraith root
yeah I've tried that but Ill try again
?
@wraith root
Awesome thanks! I've have tried the confiner but maybe playing around with that script might work
i am trying to make a melee combat system and for some reason it is not detecting that it is hiting the enemy and the debug.log it not triggering
And i do also have a attack point
You are not using any of the 2d collision callbacks functions
OnTriggerEnter2d.or OnCollisionEnter2D
@trim jay 👆
That would be in line 34 right?
Nop
?
You are using an Overlappingcircle
What is that?
Not for you for the other dud
Oh ok ._.
so what do i use instead of a overlappingcircle
couse the over lappping circle is for the collision
But you don't use for attacks it will work but it will need to be a little bit changed.
Just use one of the function that I have listed above
Those are functions they are the same as Update and start they are called by the engine when 2 colliders collide
So put void OnCollisionEnter2D()
Yes
Hey!
Was wondering if messing with basic rigidbody2d velocity was better done in fixed update?
or if its fine to do it in the normal update
sorry had to do somthing but what do i put under the void OnCollisionEnter2D()?
@signal berry always the physics operations are done on the fixedUpdate
@trim jay you can just check the documentation and you will learn about it and more things
hey, trying to write some code involving two separate colliders within a single object, without using a companion child object to act as a foe collider naming system. I used physics 2d materials to attempt to differentiate the colliders but it seems to just read them both regardless. any suggestions?
thanks for the quick response! had been lookin a bit and actually just found this post too
For some reason when i make a drag and shoot movement thing it wants to go to one direction.
what is your min and max power?
they should be between 1 and -1
since you're essentially trying to normalize the direction of your shot
That could be an issue...
You can try changing line 46 to force = new Vector2(startPoint.x - endPoint.x, startPoint.y - endPoint.y);
the min is -8 and the max is 8
I'm missing the bug somewhere
It works Thank you. This discord server is very helpful.
Heloo guys im new to Unity can you help me fix this?
note: PewPew script is in a prefab.
What's working and what isn't? We don't know what you need help with. What the "this" is inferring to.
what worked is that in codes it detected the Scripts "Stats".
what didnt worked is that when selecting the "Stats" in components, I cant find it.
is this possibly a bug?
Well, unless you have a prefab stat object (one that has a component of type specific to prefab) the list will be empty. What did you think was supposed to be visible?
That's in the assets folder.
If the Stat was a struct, you would have a default value to manipulate. Else assign it a new Stat as default or it'll be null.
Where it'll expect a reference (a component implying that an object exists in the scene with said component or possibly as a prefab) if null.
I'm sorry im a newbie to Unity, there are some term you used and I didnt know what it is.
is it okay if I asked a question maybe later?
Default meaning on declaration give it an initialization.
Should always be fine to ask questions here.
Thanks.
Let me explain..
PewPew is the bullet (prefab) who has the damage.
do you think it will fix the problem if I put the damage (code) to the gun instead?
Try public Stats stats = new Stats(); (assuming stats isn't a Monobehaviour).
Stats is a monobehaviour.
(Stats : Monobehaviour)
Then you'll need a reference to the object with component stat (in the scene or assets folder as a prefab)
If in the scene, drag and drop said object into that slot. Same applies if a prefab (know that one references an instance the other references a prefab)
Something of the sort.
Something messed up... when I play the game, Unity disables movement.
Someone have any idea how to fix this?
If I want to add the players x velocity to a projectile when it's shot how can I do that?
I've tried doing cs Vector2 PxV = new Vector2(rb.velocity.x, 0.0f); bullet.GetComponent<Rigidbody2D>().AddForce(Vector2.right * BulletSpeed + PxV, ForceMode2D.Force);
nvm
i need help for when you presse a UI Button its put all UI Invisinsible
im a beginner code
put all other UI in an array, and disable them if you click on a specific button
Look into CanvasGroup, it's the most efficient way
i mean in a script when you clique a button UI it disappear all the UI ! (the button disappear to!)
Put all the UI inside a empty rect transform, then do rectTransform.gameObject.SetActive(false);
Easiest way
Or you can go a step further and use canvas group
ok what a rect transform
Its a transform type that is used on canvas
ohh ok
Right click the canvas, create empty
ok then?
Drag everything into there, then just enable/disable that gameobject
using UnityEngine;
public class MyClass : MonoBehaviour
{
public GameObject canvasPanel;
public void CanvasThing(bool state)
{
canvasPanel.SetActive(state);
}
}
Put the script on any GameObject in the hierarchy, then use the function to set it false or true
ok thx
I'm attempting to use this code : https://pastebin.com/S8Awp6Za to make an enemy shoot a projectile in attempt to stop the players projectile, yet it doesn't react. Does anybody know any way to fix this?
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.
take a different approach on the issue
create a larger circle collider and use that as a.. onColliderEnter -> try to stop the bullet.
I just realised the entry condition (not shown in the script) only detected the player, not the bullet
GameObject tempProjectile = Instantiate(projectile, weapon.position, Quaternion.identity);
// Get mouse position and get the shoot direction
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 dir = mousePos - weapon.transform.position;
// Add velocity towards the mouse position
tempProjectile.GetComponent<Rigidbody2D>().velocity = dir * speed;```
I am trying to shoot a bullet towards my mouse position. It works, but the speed of the bullet is slower/faster in certain directions? It is not every direction the same speed?
Oh it depends on how far away you are clicking from the object
Any idea on how to solve this issue?
normalize
the dir?
Vector3 dir = (mousepos - weapon.transform.position).normalized;
yes
always normalize vectors that are supposed to serve as a direction
Still having the issue, I tried that 😦
are u sure
ok
{
// If the left mouse button is pressed
if (Input.GetMouseButtonDown(0))
{
// Spawn projectile
GameObject tempProjectile = Instantiate(projectile, weapon.position, Quaternion.identity);
// Get mouse position and get the shoot direction
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 dir = (mousePos - weapon.transform.position).normalized;
// Add velocity towards the mouse position
tempProjectile.GetComponent<Rigidbody2D>().velocity = dir * speed;
}
}```
This code
strange
that looks like exactly what would happen if it wasn't normalized
could there be some additional script either on the bullet or on the object spawning it that you forgot about that could be adding extra undesired force?
No, this is the only code it has
Is there a 2d version of transform.lookAt()?
u can make ur own
actually tbh
transform.right = target.transform.position - transform.position;
lol
It has a worldUp parameter
@drifting elk how about
Vector3 dir = mousePos - weapon.transform.position;
dir.z = 0;
dir = dir.normalized;
tempProjectile.GetComponent<Rigidbody2D>().velocity = dir * speed;
Oh, damn
What exactly was the problem and what does normalize do?
it would seem the mousePos and the object have different Z positions, then?
because setting the z of the direction to 0 is the main thing that solved the problem, right?
oh
its a combination of the z and normalize
so, when u do
b - a
where b and a are position vectors
you get a line going all the way from a to b
this means if b is far from a, the line will be long
if close, the line will be short
if u multiply the line by the number two, the line gets twice as long
this is undesirable for direction vectors
ah yeah
so u normalize, to make it a length of 1
so that u have more control over the final speed/direction
Thanks 😄 !
if(player.position.x - 10 < transform.position.x < player.position.x + 10)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
}
It says : CS0019 Operator '<' cannot be applied to operands of type 'bool' and 'float'.
Im so confused 🥴
nevermind, i figured out.
Anyone know why this returns 0, 0? I have 2 logs, it has one with the correct location, but then it gets 0, 0!
@still tendon you will need to use and operator orthe pr operator
Between each condition
yep i figured out
i have another problem...
I am trying to attach a gameobject to a prefab's public variable, but i just can't drag it into the field, nothing is happening
What is the type of the object uou are trying to attach, also make sure that you are saving the prefab when you drag and drop the game object
Raycast doesn't return a Vector2
it returns a RaycastHit2D. So the first time, it is actually assigned a Vector2, but the second time you are giving it something else (a RaycastHit2D). I have no clue how it isn't erroring (unless it is)
I want to attach the Transform component of a game object
here
Dragging in the whole gameobject to that slot doesn't work?
assuming both of these objects are in the scene?
W̷͎̒H̶̲̑O̷̐̍ ̶̆̉P̸͐̒I̷͆͜N̸͎̎Ḡ̶̋Ė̵̫D̷̊̂ ̷̒͝M̵̏̐E̸̗͌
lol
no
You need to instantiate the player, then get a reference to the transform after it has been instantiated
You can just use FindGameObjectWithTag or similar ways
ping
It is a point
i mean, the player is on the scene but not the prefab
but some other components are working just fine, that's why im confused
Whoops, then I guess it is returning 0,0 by default, since I doubt it hit anything
and structs cant be null
It returns 0 for not hitting anything!!?!??!?!?!?!??!?!
Why can't it just give me the point where it didn't hit anything?
Cache the raycasthit, then do if (hit)
because its checking the whole line, so there are many points that it didn't hit anything
do you want the end point or something?
Scene objects shouldn't interact with asset folder objects unless you are just instantiating them
ok
Got tired making so many if else statements for the ray I just made a function LOL
And now its still not working. Good job, me.
Think I fixed it
Function is grey, You're probably not usingi t
its fixed
and I am using it
idk why its grey
not grey anymore
I just added an exponent to my camera and it is having the opposite effect
its slowing it down
cause it is too slow originaly
I'm trying to use a button in a menu scene and I'm using this code to go to the first level, but for some reason it simply just does nothing.
This is the code ```cs
public Button Button1;
// Start is called before the first frame update
void Start()
{
Button btn = Button1.GetComponent<Button>();
btn.onClick.AddListener(clickTask);
}
void clickTask()
{
SceneManager.LoadScene("Level 1");
}``` and in the button it's using the correct function.
I would just make clickTask public, and drag it onto the OnClick event on the button component in the inspector
Edit>build settings. Make sure both your scenes are in the black box provided.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2D_1 : MonoBehaviour
{
public float speed = 10.4f;
void Update()
{
Vector2 = transform.position;
if(Input.GetKey("w"))
{
pos.y += speed * Time.deltaTime;
}
if(Input.GetKey("s"))
{
pos.y -= speed * Time.deltaTime;
}
if(Input.GetKey("d"))
{
pos.x += speed * Time.deltaTime;
}
if(Input.GetKey("a"))
{
pos.x -= speed * Time.deltaTime;
}
transform.position = pos;
}
}``` saying POS does not exist.
Wait
im dumb
I didnt
put a pos in Vector3
u don't need so many IFs
u can use Input.GetAxis, y'know
public class Move2D_1 : MonoBehaviour
{
public float speed = 10.4f;
private void Update()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
pos += new Vector3(x,y,0).normalized * speed * Time.deltaTime;
}
}
A,S,W,D are automatically mapped to it
which can be changed in ur project's input settings, if u ever change ur mind about which keys to use
what resolution am i supposed to have my game at with the 2D pixel perfect camera component?
there's a reference resolution field in the component
does that mean the game resolution is supposed to be that resolution?
i got no idea how to program 2d but LETS GIVE IT A TRY!
Hey i cant find any tutorials at all about 2d weapons?
i have a charecter coded ready to go. Now i want him to be able to pick up various weapons or at least swap between some i make
@boreal saddle Bro there is 1 tutorials Of 2d Weapons
in the discord?
actually got another question lol. I have a code set up to flip the player depending on the x input (isFacingRight). I just added a feature where you can aim where the moue button is but now when you flip the aim in inverted
how can i cancle out that inverting ?
ooo couldnt i copy my is facing right code onto the aiming thing
Can someone explain how to make a Terraria style Tilemap with tiny cells and procedural world gen ?
@brittle lagoon so bassically, when your character dies/get hit maybe do something like
if(hp = 0) {Invoke("respawn", 2f);} //wait 2 seconds} void respawn() {Instantiate(yourCharacter);}
Hi, I'm using Tilemap Collider 2D for my map, but the player tapping a frame gets stuck.
The game is platformer and I am using the transform.position.
Does anyone know how to fix it?
can someone explain to me how to draw sprites on a grid through comand and make a 2D procedural terrain out of it ?
help :3
@warm cedar use a 2d physics material on the colliders that the player gets stuck on
@atomic patrol check this article
https://medium.com/pumpkinbox-blog/procedural-map-generation-with-godot-part-1-1b4e78191e90
I've been trying that, but it doesn't work.
ye but not 2d topdown like 2d
terraria is an example
i just want to draw tiles on my grid and create a procedural generation out of it
@warm cedar what's the settings you set for the material
I have tried 4 combinations.
With friction, without friction, with bounciness and without bounciness
@atomic patrol in that case you can draw the tiles on the grid and make bunch of them with different appearance and shape turn them into prefabs and instantiate them randomly.
If your idea is to do a procedural generateda dungeon you can take a look at this tutorial
https://youtu.be/qAf9axsyijY
In this beginner unity tutorial we will begin making a random dungeon generation !
We will first of all discuss what are random dungeon must and must not have and follow up by making our rooms and doing some programming with C# !
SUPPORT ME : https...
I have uploaded a small video of the problem in case I miss something;
https://drive.google.com/file/d/1OR_Ft1DnY13--xN8F5PAyPJFXhb-0E45/view?usp=sharing
I will take a look at it
The issue is the colliders. You have 2 ways
One is 2d materials
Second is to use a raycast from the player position to forward direction and get the normal of the collider the ray cast hit and if it is 90 degrees then add for in the opposite direction
what resolution am i supposed to have my game at with the 2D pixel perfect camera component?
there's a reference resolution field in the component
does that mean the game resolution is supposed to be that resolution?
it's a side scroller 2d procedural terrain not dungeon :p
Reference Resolution is the original resolution your Assets are designed for.
So in other word it depends on the canvas size you used when you created your assets (sprites)
I have no idea then, sorry
can someone explain to me how to draw sprites on a grid through command and make a 2D procedural side scroller terrain out of it ?
well when I made a build of the game the size of the reference resolution it was really blurry when I maximized it
Hey guys, I'm having trouble using a Sprite Renderer(with a billboard) with a 3D Mesh. When my sprite gets close to the mesh it goes through the mesh. How could I avoid it?
isnt that ragnarok online
"yes". i'm rebuilding the client
is the angle of the billboard going throught the mesh? you can check in scene view in 3d mode
not sure ro had any 3d thought
dont know how you can flatten all this on the same z position to make it sort correctly since its 3d objects
the angle of the billboard going through the mesh, yes
well, I guess it had since these models are read from ro data file
one thing is sure is you have to sort character over all other layer using the feet pivot of the character, if the map is all 3d then instead of y like a 2d game you would use the z
The z part is already done, the sorting kinda. I've added a sorting group to both the character and the model, however couldn't get it to work, I've tried making the character a positive value and the mesh either 0 or negative
One idea is to use one or two raycasts that is pointed downwards instead of coll.isTouchingLayers(ground)
public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);
@cobalt valley RaycastHit2D hit = Physics2D.Raycast(origin, directon, rayLength, layermask: ground)
i make this to the player can get stuck on the walls but now he can get inside of the walls
anyone know how to reduce blur with the 2D pixel perfect?
I built the game with the reference resolution but it's still blurry
in the editor it looks crisp
have you put the sprite filter modes to Point (no filter) ?
yes
is there a build setting that affects it?
because everyting looks good in editor
this might help
I'll try it out
let me know if it made the trick:)
mip maps were all off
I changed the max size but that doesn't seem to affect anything
hello i was trying to keep my player from bouncing off the wall and from sticking to the wall when i clicked the floor button i did this and now he can get into walls
Hello guys ineed a team to do a game together to do The Completion Jam
completion?
oh
so you gona help me ?
also i've only used 3d
2d is maybe easier
maybe i can help with ideas
and maybe pixel arts and random music piece
cool
how could I adjust the physics on 2d collisions? I know that i can create physics materials and all that, but how could I further customize the physics engine? I am trying to create a ball that bounces in an "unrealistic" way, meaning that it would bounce, and then kind of slow down at its peak if that makes sense.
hey did unity delete Image type
im following a tutorial and in the video they use it but in my version it doesnt have it
In code, you'll need to have using Unity.UI;
was that to me
Yes
I have unity.UI
im talking about this thing
mine does not have the image type
I think it is not on my version
there is sliders however im trying to make the health bar go slowly down to the new health instead of cut to it
I think I need something called Lerp that moves things slowly between position but I'm just very confused on it
Hey guys, any tips on how to get a highlight red with mouse hover over a button in a way that won't affect any of the code?
https://codeshare.io/GbVPkV
@vale summit You need to use a source image before you can change the type.
Ok so basically by default the enemy walks back and fourth and I set that up by making the enemy flip when he reaches the end. However when the enemy levitates in the air (setup by a range value) Im trying to figure out how to make him flip again to always face the side the player is on
I understand the flipping part of it
just not how to make that happen by the players location
Just compare the x-values of the player and enemy's position. If the player is to the left of the enemy, it'll be smaller.
Do you know how I can make it so my enemys projectiles dont effect him
Here is my script for the enemys bullets. Im trying to make it so his bullets dont have collision on the enemy (himself)
Collision matrix
can i do it with tags?
Collision matrix
so, i wanna add spread to my shotgun, for that i want to take the firepoint.rotation and add Random.Range(-10f, 10f) but it is telling "CS0019 C# Operator '+' cannot be applied to operands of type Quaternion and 'float'' " i understand the problem, but don't know how to fix it. Help plz '^'
u need eulerAngles
and
u need pick the specific axes to modify
Vector3 rot = firepoint.eulerAngles;
//modify either rot.x, or rot.y, or rot.z
//e.g.,
//rot.x += Random.Range(-10f,10f);
firepoint.eulerAngles = rot;
x rotation = looking up and down
y rotation = looking side to side
z rotation = tilting your head to the side
or u could multiply the quaternion to rotate it
up to u
bit of a beginner question but what do when images don't actually correspond to their bounds being set and refuse to be dynamically resize instead stretching in wide steps only.
The UISprite doesn't have this issue but any custom texture I use does so it must be me being stupid
@tropic inlet i used
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation * Quaternion.Euler(new Vector3(0, Random.Range(-10, 10), 0)));
But for some reasons, my bullet is still moving straight as usual. I also tried ur code but it's doing the same thing.
I just checked if i had any other code changing the bullet's rotation, but nothing
yep
maybe you need to change the Z rotation, then?
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation * Quaternion.Euler(new Vector3(0, 0, Random.Range(-10, 10))));
ok i'll try that
nope, nothing is changing
rb.AddForce(firePoint.up * 100, ForceMode2D.Impulse);
i don't thing this piece of code is changing the rotation, but... meh. maybe ?
hmm
only one way to find out whether the quaternion multiplication is doing anything
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation * Quaternion.Euler(new Vector3(0, 0, Random.Range(-10, 10))));
print(bullet.transform.rotation.eulerAngles);
how do i check when a float hits 0?
i don't thing this piece of code is changing the rotation, but... meh. maybe ?
I don't think AddForce changes rotation
When it hits exactly 0?
yeah
That might be tough, 'cuz doubles/floats can be imprecise, but
it subtracts 1 everytime you do something
Personally
I prefer using <= or >=
with floats
due to imprecision
0.00000001 and -0.00000001 are not 0
Do the rotation is changing but the bullet is not following the rotation.
So ill try to make the bullet move by itself based on its rotation. That's my last idea 🤔
oh
i think i know why
the problem is
it's adding firePoint.up * 100 force
but
firePoint.up is not the same as transform.up for the bullet
make sure the bullet uses .AddForce(transform.up * 100, ForceMode2D.Impulse)
so i should add force to transform.up in the bullet script ?
ye
I want a collider to trigger only when the player hits the side of the cube but if he hits the top nothing happens. my player is a box collider and the obstacle has a tilemap collider.
do i have to add two colliders to the obstacle or is there a simpler way
the obstacles are also randomly spawning tilemaps
There was a thing called Edge Collider in unity
someone can help with adding UI and custom UI?
yes in a 2d game
something that will let me have a pause button( and pause menu) and some custom hearth for lifes
where can i find a simple tutorial for topdown movement
i want to make a simple Arcade style game and i dont know if the RPG movement tutorials would work
Youtube?
yes
Yeah, Youtube. 😛
what???
You're asking where to find tutorials, the answer is Youtube.
@waxen surge as the other guy said youtube has everything you need.
For your answer on the top down movement check this https://youtu.be/whzomFgjT50
Let's have a look at the easiest and best way to make top-down movement in Unity!
Get costumized art for your game with Outstandly! https://www.outstandly.com/art_for_games/?Brackeys=love
👾 JOIN THE GAME JAM!! https://itch.io/jam/cgj
Thanks to everyone participating in the planning of the jam:
BlackThornProd: https://bit.ly/2GqgkqO
Dani: ht...
@runic kite you can use the edge collider or calculate the hit direction bu using collider.contact point and see if the vector from the hit point to the center of the cube is equal the up vector normalized
Hey, i'm setting at runtime a BoxCollider2D size by taking the difference between the Y pos of two bones on the model... but the size i'm getting out of this creates a collider that is almost twice al tall as the distance between the two points... am i making a dumb mistake somewhere? (PS it's a 3d model in a 2d environment)
BoxCollider.size = new Vector2(
BoxDefaultSize.x,
Mathf.Abs(head.position.y - Mathf.Min(leftFoot.position.y, rightFoot.position.y))
);
it uses an already existing player for it but all i have is a sprite that i cant add scripts to
how do I add collision to this capsule in between the image
it isnt a platformer, you use the arrow keys to move
@still tendon if you just want the bottom / "feet" to collide, remove any default collider, then add a circle collider, and modify the collider position in the inspector to be down where the "feet" would be
oh yeah that's what I had in mind
ok
I'll try
The new input system seems to not fire an event for the second key in a combo of two keys, both of which are assigned the same 2dVector Action.
Is there official documentation somewhere that explains how to use the 2DVector action bindings?
How can I use a render texture to draw directly on a canvas Raw Image? Almost every tutorial I've found (been looking for hours) explains how to implement this for drawing on 3D objects but not drawing on UI.
The exceptions being these two:
https://www.patreon.com/posts/rendertexture-15961186
http://hannahro.se/blog/tutorials/2019/02/18/paint-game-part-1.html
My main conundrum is that I don't want to paint on the UI based on mouse position or input (as these two tutorials do) but instead use the screen position of a gameObject in the scene as my "brush" so to speak. I understand how it all works but I am novice C# programmer when it comes to syntax
Hi everyone, I have a problem and I dont know how to fix this
When i want finish lvl in my game a must go to the end maps and stay in one place
I want add extra point if you will be there before clock show 0 seconds
But I have this error
Fist I want that see this extra points in console
this is error:
NullReferenceException: Object reference not set to an instance of an object
ExitThisLevel.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/skrypty/ExitThisLevel.cs:22)
i tried his two comends:
timer.addPoints();
GameObject.Find("GameMenu").GetComponent<TimeManager>().addPoints();
@zenith saddle It doesn't find TimeManager component on GameMenu object, and calling method on a null object triggers the error. You should always use direct references when you can to avoid that.
Right
But I trying fix this and I can't come up with
ok, i have right 😄
I should find Timer, not GameMenu 😄
and Timer is in GameMenu
Being consistent in naming game objects same thing as scripts they contain would help as well
we make a game to join the game jam so we need some helo any one want to help us ?
Hi i need some help on a script that can change a colour of a prefab (example Green) when a button is pressed
this i also android
Hey, Im planning to make a game like Terraria for educational purposes, but the world design will be created on the Editor using tilemap(not procedural). I would like to get some advice before commiting to much into it. Is it going to be expensive (to the point of being unplayable) on the computations if I have the entire world loaded and rendered at once?
@leaden veldt you will need to instantiate the prefab first then do something like this.
GameObject objectToColor;
objectToColor = Instantiate (....);
//This method is going to be assigned in the inspector of the button OnClick event or use it with code.
Void changeColor(){
objectToColorkubus.GetComponent<Renderer>().material.Color = Color.red;
}
thankyou @clear tusk
Hey everyone, me again. I've been searching for weeks about ordering but couldn't find anything that would point me to a direction that could help with the issue I've described here https://forum.unity.com/threads/sorting-sprite-renderer-over-a-mesh-renderer.1029448/
TL;DR from the forum link:
I have a sprite renderer with billboard and a 3d mesh is culling part of the sprite. Sorting layers don't seem to work neither sorting groups
@sterile timber what does the 3d scene look like? the character sprite is intersecting with the geometry I assume?
also this might be of interest
bgolus has a good breakdown of the respective rendering techniques
Well, I was searching a bit more and found out that if I keep my sprite straight and change its Y scale based on the camera angle I can achieve the billboard effect
the sprite intersects with the mesh
an interesting solution, I had something similar set up and rejected it eventually because it created more issues than it seemed to solve further down the line
I assume before you had the sprites angled to align with the camera?
hence the clipping
exactly
the billboard just copied the camera's rotation
Ive also tried bgolus shader as posted here https://forum.unity.com/threads/problem-solving-2d-billboard-sprites-clipping-into-3d-environment.680374/
it sometimes makes the sprite disappear
however it fixes the clipping
interesting
A screen facing sprite already has the same z across the entire surface, that’s in fact kind of the problem.
how did he solve this?
stenciling?
not sure what stenciling mean
nvm, I guess if what you have working now works then cool. I'd love to work out the shader code to do this:
The even more advanced shader only option would be to output the z as if the sprite is a vertically aligned sprite, but keep the appearance of a screen space sprite.
as it seems to be the most 'correct' solution
and makes sense logically but for the life of me I couldn't write that
some sort of vertex shader manipulation I expect
😉 oh god, don't get me started on another project
a shader won't kill 😇
also - does anybody know much about velocity Verlet integration who could answer a couple of questions I have?
The new input system seems to not fire an event for the second key in a combo of two keys, both of which are assigned the same 2DVector Action. Is there official documentation somewhere that explains how to use the 2DVector action bindings?
@sterile timber can you use a vertical billboard but project the texture onto it in screen space so it faces the camera even though the geometry isn't?
I think I've done that on my last try. The X rotation isnt touched anymore. Instead I increase the Y scale by 1 + cos(angle)
How could i clamp the camera to perfectly collide with a exact coord?(blue line) Depending the resolution i can see out the "map".
It matches correctly top/bottom but left/right nope...
Noticed it maches at 1920*1080, how could i do it it matches on every res?
I'm trying to do a basic floor detection but I'm getting a strange issue where the OverlapCollider seems to detect overlap before it should. (added gif with visual)
Code to do detection:
void FixedUpdate()
{
//Reset value
isLanded = false;
//Do cast to see if any collisions are present
Collider2D[] hit2D = new Collider2D[8];
int floors = collider.OverlapCollider(contactFilter, hit2D);
if (floors > 0)
isLanded = true;
}
What am I doing wrong?
Hello, what is the preferred way to apply a force to a UI element (button)? I would like the menu to "fly away" after clicking "start game".
I tried to add a collider and a rigidbody to the button but it doesn't seem to do anything
(there's an area effector below which works fine with other game objects)
On a UI element? :\ I'd say either make it a sprite or use an animation/tween in script.
how would i make it a sprite?
Place a sprite in the world with a 2Dbox collider on it then use
void OnMouseDown()
{
// do stuff
}
may want to make it a trigger collider unless you want it to interact with stuff
ok so it's basically creating a button from scratch
thank you for your advice, i will evaluate this option
Fixed: setting navigation to none in the inspector did the trick.
Original question: Is there a quick way to stop a button from getting clicked on by the space bar?
does anyone know how to create a limit so that the plater dosent just keep falling off into oblivion everytime he goes off the map?
@brittle lagoon
Something like this
If(player.transform.position.y >= limitdistance){
//Do something
}
Or
If(Vector.distance(transform.postion, previousposition)){
//Do something
}
previousposition this variable is going to be a vector 2 and it will have the last position that player was in before it falls of
//Do something
do i create a speerate scirpt
or do i include this in the player script?
Just include it in the player script but don't forget to have a condition for when the player is Dead
sorry for hbeing irritating but this is really important for my school project
for this code
//Do something
}````
do i just paste it in?
or (im guessing) im gonna need to modify it and if so how do i do that?
Can you show me the player script and what do you want to do exactly when the player falls off
you can dm if you don't want to past it here
is there any reason why Ground check stops working when you enable Composite on tile maps?
how can I enable UI through script/
Are you wanting to switch UI for a main menu or enable something on screen during gameplay?
https://hatebin.com/fegealfozj
[SerializeField] private LayerMask GroundingLayers;
private bool IsGrounded()
{
float extraHeightTest = 0.5f;
Vector2 bounds = gameObject.GetComponent<Collider_Identifier_cs>().CollisionCollider.bounds.size / 2;
Color color;
bool isGrounded = (Physics2D.BoxCast(rb2D.position, bounds * 2, 0f, Vector2.down, extraHeightTest, GroundingLayers));
if (isGrounded)
{
color = new Color(0, 255, 0);
} else
{
color = new Color(255, 0, 0);
}
Debug.DrawRay(rb2D.position + new Vector2 (bounds.x, 0), Vector2.down * (bounds.y + extraHeightTest), color);
Debug.DrawRay(rb2D.position + new Vector2 (-bounds.x, 0), Vector2.down * (bounds.y + extraHeightTest), color);
Debug.DrawRay(rb2D.position + new Vector2 (bounds.x, -(bounds.y + extraHeightTest)), Vector2.left * bounds.x, color);
Debug.DrawRay(rb2D.position + new Vector2 (-bounds.x, -(bounds.y + extraHeightTest)), Vector2.right * bounds.x, color);
Debug.Log(isGrounded);
return isGrounded;
}
I am trying to create a ray-cast ground-check box and have thus-far been unsuccessful in detecting the desired result. The visual draw rays are effectively the desired detection box. how can i properly translate the 4 drawrays to a boxray
So I'm trying to compare the edges of my sprites to find the closest possible match to my tiles
so I go along the edge of each sprite pulling the pixels that line up with the next tile
and get the absolute (pixelA - pixelB)
then I add that all up and get the difference value
and find the tile with the lowest of this value
it doesn't work very well
anyone know of a better way?
Do you have to work on pixels? Why not Unity Units and scale?
Ok so I have several objects in my scene setup so when I click them a UI panel pops up with information about that object. I've gone with the simple method of a script attached to the object that opens its UI. The problem now is my info panel UIs end up opening on top of eachother... I know there is likely a more efficient way of handling this rather than placing "Set.Active(false);" on every single object's interaction script...
I've gotta gather there's a way to have one script that handles opening and closing UIs for all specified objects, just not sure how to set that up
@opal socket unity units and scale?
I'm trying to find the closest match for a given tile out of my tileset
it's not an issue of positioning, it's an issue of finding the appropriate tile that fits next ot it
Ahh sorry misread
can someone help me figure out why this isnt detecting collisions
isGrounded = Physics2D.OverlapCircle(groundcheck.position, .2f, WhatIsGround);
Not without more context
- Have you initialized WhatIsGround to your desired layers?
- Is your ground object actually set to the ground layer?
- Is the groundcheck in the correct position, and a child of your character?
- is .2f actually enough radius to touch the ground from the groundcheck's current position?
I've realized my stupidity, i created the layer and then never assigned it
Honestly, that is an easy mistake to make
In my opinion, creating the layer should automatically assign it to the object you just created the layer on
but it doesn't.
Can someone help me? I implemented moving right or left and jumping for an android game im trying to make. I have this issue where if i jump and then move the player does not fall but kinda floats and slowly falling
So i probably need to change my code
Are you setting your y value to 0 when attempting to move via X?
Anyone use Sprite.Texture.GetPixel()?
The values at the coordinates I'm specifying are not accurate
and I don't know why
Is there some scaling of the texture I have to consider?
nope that's not it, I'm actually getting pixel values that don't even exist in the sprite
Yeah, that sounds like what he's prolly doing
@earnest trail make sure u don't modify the y
Let me check
these getpixel values don't make any sense
I mean im a beginner so im looking online mostly for code
Vector2 vel = rb.velocity;
vel.x = Input.GetAxis("Horizontal") * speed * Time.fixedDeltaTime;
rb.velocity = vel;
obviously, input shouldn't be taken in FixedUpdate
My previous movement with wasd was really nice but because its on android i changed it to using arrow keys and changed the whole code to something very simple
but this is the basic idea
u should only change x from horizontal movement
Ok one sec
im using this:
void Update()
{
if (moveLeft)
{
rb.velocity = new Vector2(-moveSpeed,0f);
}
if(moveRight)
{
rb.velocity = new Vector2(moveSpeed, 0f);
}
}
see, that 0f is the problem
isnt that 0?
u are setting vertical velocity to 0
replace each 0f there with rb.velocity.y
hm ok let me see
ah its perfect now
Is there any tutorials to explain a bit these vector2 vector3 , rigidbody etc? Because ive seen a million ways people use to code something and its confusing which one i should use every time
Speaking for unity
Also i have 2 more minor issues if you can help
Watch this video in context on Unity Learn:
https://learn.unity.com/tutorial/vector-maths
A primer on Vector maths - as well as information on the Dot and Cross products.
a vector can be one of two things:
- a position
- a direction
hm
yes
both position and direction right
yes
aight
Ok i have another minor issue. Im using a background and some assets ive found to create the environment
my player is a ball
when i move it
the background does like little vertical lines
sometimes
its really minor but its noticable
its lines as if the background tiles are not correctly connected or something
like those lines from old movies
i have the same issue but with vertical lines, i was wondering if it's the tilemap not updating in time when the camera moves
probably don't have the camera setup right
It's a common issue, I don't know of a good tutorial on it, but you need to make sure your camera , pixels per unit and so on are all in line with each other
hm so its a camera issue
Awesome il take a look at it. Also something last. Is there a way to change the collision box of some tiles?
As you can see the collision is a bit above
I haven't mucked with collision yet, but it should be editable
alright, thanks.
@earnest trail i've found an answer to the flickering tilemap in here: https://www.reddit.com/r/Unity2D/comments/8g74ft/tile_flickering_problem/
Thank you. I was looking right now for a while and couldnt find anything
Let me check it
People say about this pixel snap but i cant find it anywhere
no thoughts on the getpixel issue?
Getpixel?
yeah I'm running into weirdness when comparing pixels in sprites
Whats getpixel?
Il try adding border on the tiles
Maybe this will fix it
nvm
So whats the approach on level making? Should i make some variations and make it so it randomly adds to it? Because im thinking something like hill climb racing where its a big horizontal level and you upgrade a little bit your stuff so you can go a bit further every time
those hill climb distance games usually don't have random terrain features
because if you do then how far you get is purely dependent on your luck, rather than getting a little farther each time you get upgrades
the other styles of the game do have randomality (like the ones where you shoot something out of a cannon, or have something that fly's) so I guess it could work
the easiest might be to define "sections" of map that you randomly decide one after another
@earnest trail i kind of fixed it, my tiles had Pixel Per Unit = 128, i changed it to 127.5, re-created tileset, re-painted the tilemap.... and now the lines are gone. My only concern is if this will impact the rest of the level design and/or the tilemap colliders
yeah not sure you want to be shaving off a bit on pixels per unit
that sounds like a headache down the road
Crap, haven't thought of that. You're right
yeah that's my worry, better a whole pixel?
I gave up for today. Wasted like an hour but couldn't fix it
you might need to use the pixel perfect camera
and look up a tutorial on how to determine the settings for it
if you get the settings just right it should tile everything without issue
i'm using the CinematicVirtualCamera, is that the same of the pixel perfect camera?
no
@earnest trail If you make sections (like how the level editor works in the NES game excitebike) and then make a determination of the difficutly of a certain section (how much fuel it costs to pass and such) you might be able to come up with a system to randomly generate the level in a way that doesn't lead the player to having drastically randomized drive distances.
Im using that too
And took me a while to fit it to the level
So it doesnt go outside of the level
Sometimes it's ok to have a bit of the sprites go off the sides of the level
No i mean that it was displaying parts where there wasnt tiles
So it was really ugly
ahh
well that's dumb
sprite.texture.getpixel is the whole texture
so I need to use the rect for the spritesheet to get the right position
Is this right?
Color32 pixel = texture[rect.y + yPos * rect.width + rect.x + xPos]
Vector3 mouseScreen = Input.mousePosition;
Vector3 mouse = Camera.main.ScreenToWorldPoint(mouseScreen);
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(mouse.y - transform.position.y, mouse.x - transform.position.x) * Mathf.Rad2Deg - 90);
help not work
im instatiating character 4 seconds after a procedural level is made player not rotating to face cursor
help
The new input system seems to not fire an event for the second key in a combo of two keys, both of which are assigned the same 2DVector Action. Is there official documentation somewhere that explains how to use the 2DVector action bindings?
best documentation you'll find is on unity's site but it's not easy to understand
I feel like I must be doing something wrong
I've got two box colliders set up, one is a trigger one isn't, when they overlap the trigger has some code on it in void OnTriggerEnter2D to make it do Debug.Log calls but nothing is happening
nope, it needs one?
I'll try
yeah it needs one
in my head, I'm like "don't do that, you don't need physics objects"
but I guess it's fine
if i deleted my main camera can i make another using the main camera tag
hmm
ok im having problems with my character facing the cursor and thats not it
could it be that the update function is bugges
bugged
because it faces a point when its spawned
Vector3 mouseScreen = Input.mousePosition;
Vector3 mouse = Camera.main.ScreenToWorldPoint(mouseScreen);
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(mouse.y - transform.position.y, mouse.x - transform.position.x) * Mathf.Rad2Deg - 90);
thats in the update function
its not updating the mouse cursor
it thinks its at a point
hmm indeed
hahah ok
got it
its saying 00
but
its supposed to rotate on the z axis anyway
ill change the code
-0.70710680
thats what its returning
well debugging the mouse position seems to return the mouse position
Vector3 mouse = Camera.main.ScreenToWorldPoint(mouseScreen);
i think the problem is here
i dont think it has a reference to Camera.Main
no it does
hmmm
2d
i don't think printing the .x of a quaternion will be very useful
unless u can actually interpret them
they are some complex 4-dimensional representation of rotation
i see
quaternions are complicated af, yea
that's why
.eulerAngles exists
easier-to-understand three-dimensional representation of rotation
vector2 isnt it
i have been
haha all good
its not that
i debugged that
Quaternion.Euler i think its already using that
im sure its something about the project/not code
it was working b4
but i dont know what happened i literally changed a script to mess with procedural spawning and it stopped working
i think i found a key to the puzzle
mouse isnt updating
got it to work
the method used is screentoworldpoint
and that needs a specific z value set in order to see at which point of the ray cast from the camera to u se
thanks for the help boys
need help with this error
just an error you are getting in the editor?
Did you remove some sprites or something?
can you edit cameras while they are displaying
like changing position n such
im having problems with it
idek anymore
?
So i need help for jumping when i jump multy times its jump multyple times . i want that when you jump it wait 3 second
but i dont know how to do it
here my code
I CANT PUT MY CODE
AHHHHHHHHHHHH
@smoky loom Code posting guidelines are pinned in #💻┃code-beginner
!unmute 427868911279800320
DarkFish#3634 was unmuted
ahhh thx
So i need help for jumping my probleme of the script is that when i jump multyple times its jump multyple times . i want that when you jump it wait 3 second
but i dont know how to do it !
Thats my code (There is the movement code to)
You want to deliberately implement a 3-second delay prior to each jump?
decrease a float in update or use a coroutine
yes i want to do it
i dont understand
when you jump, set a float to 3.
Each frame, subtract Time.deltaTime from that float.
Only allow to jump if that float is <= 0
i dont understand try to show me a script
Which part do you not understand? I can give you a script, but there's no point if you just copy it
all of it that i dont understand
im not a pro of coding all i do is following tutorials
private float timer = 0f;
private void Update()
{
if(timer > 0f)
timer -= Time.deltaTime;
if(timer <= 0 && isGrounded && Input.GetButtonDown("Jump"))
Jump();
}
private void Jump()
{
//Perform jump
timer = 3f;
}```
and where shuld i put it?
it's a good idea to learn programming basics before doing gamedev
it was laid out in a pretty easy-to-understand way
Ok!
console apps are the best learning environment
I have this code to be able to move my character everywhere I want, and it worked perfectly fine. But I decided to move my character only left to right so on the x axis. Once I remove my y axis code, it doesn't work since vector2 doesn't have another float. Any help?
just change newYPos to transform.position.y this way you don't move the Y position
i go by memory but isn't transform.position.x just a getter? You cannot modify it directly
yeah it's just a getter, cannot modify it directly. But if you don't want to allocate a new Vector at every Update you can have one global Vector in the class and use Set to change the values on Update
It worked, thanks :)
im trying to do a camera script that moves the camera to a empty on rooms of a dungeon
i just cant get it to work
the script is on the camera btw rn im just trying to have it follow the player
excuse me, I'm having some issues related to the jump movement in my game
as you can see, this is my RigidBody
my character script settings
the issue is when I jump it ascends with great speed, however, when he falls, he does slowly
https://pastebin.com/EZZgeG8Y here is my code. If you could help I would appreciate it greatly.
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.
@shell wadi if the issue is the slow falling you just need to play with the linear drag and gravity scale in the project settings.
For the jump speed make sure you are multiplying with the time.deltatime or time.fixeddeltatime if you are using physics and make sure all that is inside of the fixedupdate
all right, thank you very much
anyone have any ideas why my code isnt working
@valid dune what exactly do you want your code to do?
I'd say, make sure that there are no nullreferences.
Using GameObject.Find() like that isn't usually a good idea
Well it's just trying to set the camera position to the player position with an offset on the z
Should've commented out the first two lines in start
You think the null references are the problem?
how can i make a gif sprite, i have the gif i want to use but i don't know how to use it
you have to make a spritesheet
use this
the problem on my code was i was running 2 coroutines at the same time and having them end at the same time setting a bool to true before the camera script could do anything
i realized i could just enable the camera script when i needed it from the first coroutine
weird bug with smoothDamp here https://youtu.be/CT-JEaMbkqg
idk if im allowed to link my vids but there it is
how can i make a save and load System with rpg style?
which one? nvm im doing something else
GameObject.FindXXX all suck
Screw find.
@shell wadi try this https://youtu.be/7KiK0Aqtmzc
Eliminate the low-gravity feeling of a physics based jump with four lines of code. Actually, just two lines. The other two give you the ability to control jump height based on how long you hold the jump button.
Inspired by the following GDC talk: https://youtu.be/hG9SzQxaCm8
Support Board to Bits on Patreon:
http://patreon.com/boardtobits
Chec...
the character controller in Unity doesn't allow me to put it in because it conflicts with the RigidBody2D. What do I do?
Make a custom 2D Rigidbody controller, character controller doesn't support 2d
Hey, I've been having an issue with Physics2D.IgnoreCollision, as it is not properly ignoring the collision. I'll send a pic of my code.
I actually print debugged the values the ignore collision returns and as far as I could tell, they should be good.
One weird quirk I noticed is that if you apply velocity to the rb after IgnoreCollision line, the bullets will actually move through each other properly however it will still have the initial collision halting velocity.
So some context: 2 players shoot bullets at each other, and the bullets should travel through each other but it seems on intial impact, it just halts the velocity due to the collision, but it seems the ignorecollision does work right after they collided.
Like there seems to be like a singular frame where the collision happens before any of the code applies.
Alright I managed to fix it by messing around with different things, I ended up making the bullets "triggers" and used OnTriggerEnter2D instead. But I still don't understand why the one works over the other, so I would still appreciate if someone could explain that to me.
Hello. I need some help with 2D coding. I have a object parent and a bunch of child objects and I want to be able to setup the index of each child, any idea how I can do that?
How do you setup 2d player controls like moving around. I am making a platformer game btw.
There are like a million tutorials for that.
I've tried a ton of them but they don't seem to work
Hey I am new on this discord and have a problem with an prefab-spawner using the "instantiate" command. Everytime I try to load the prefab a "Index was outside the bounds of arry"-Code appears. Can someon tell me, what this means and how to fix this problem?
this is the full error code
it's saying, on line 17 in your Spawner.cs script,
you tried to access an index beyond the bounds of your array
e.g.,
int[] arr = new int[3];
print(arr[42]);
arr[42] in this example is way out-of-bounds
there is only arr[0], arr[1] and arr[2] because arr is of size 3
@karmic storm
Hmm seems strange. I checked all of the code but I think this shouldn't happen.
Can I send you a screenshot of the CS-code?
It'll be easier if you used either hatebin, Pastebin or Github to paste the code as text instead of a screenshot
but if the code is small enough, yea, a screenshot would work
Oh okay. I forgot to change a value in the unity interface. Finally solved it but thanks for help :)
if (Input.GetKeyDown(KeyCode.Space)) { //do stuff }
Thanks
yw
bye
@still tendon Don't cross-post
Pick one channel
Then delete your original post to not solicit split answers
I am having a bug right now where in my game which is a top down shooter where the bullets get instantly destroyed if the player is shooting downwards
Ive checked my code I dont exactly know what is causing it
If someone could help I can share my code if you want
Oh wait no I figured it out!
The bullet is colliding with the players hitbox!
So I guess now the question is, how do I make it so the bullet doesn't collide with the player?
But I still want the player to be able to collide with obstacles
@rigid juniper Look into Physics2D.IgnoreCollision stuff
you should be able to do that on creation/collision detection
you need both objects to have a collider and you'll need to be able to access them both
so for example in the player control script you could do like:
var bullet = Instantiate(...);
Physics2D.IgnoreCollision(GetComponent<Collider2D>(), bullet.GetComponent<Collider2D>());
Ok thanks!
you could i make my object point to mouse, is there a .pointTo function
https://youtu.be/LNLVOjbrQj4 This video makes the player point towards the mouse, so you could just apply that to whatever you want to point towards the mouse
Let's have a look at the easiest and best way to make top down shooting in Unity!
Check out Jason's courses! https://game.courses/mastery-course-brackeys-bonus/?ref=21
Unite Copenhagen: https://unity.com/event/unite/2019/copenhagen
Armored Soldiers: https://bit.ly/2Zqqn9P
Warped caves: https://bit.ly/2PsOyzS
Tiny RPG Forest pack: https://bit....
I could make a function for u
void PointAt(Vector2 target){
Vector3 dir = (Vector3)target - transform.position;
dir.z = 0;
transform.right = dir;
}
or
void PointAt(Vector2 target){
Vector3 rot = transform.eulerAngles;
Vector3 dir = (Vector3)target - transform.position;
rot.z = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.eulerAngles = rot;
}
haven't tested
Hey! I've made top down shooter, and it works like the video above. My problem is that I've added screen shake to my game, but the thing is that the screen shake changes where I'm pointing at. I want for example be able to continuously shoot straight, but the screen shake makes me shoot wobbly. Any ideas how to fix it?
projectile
i was thinking of getting the screen shake camera offset and just subtracting that from the mouseposition
lets say that when the screen shakes my camera moves 1 unit to the right, what i would do is just subtract my mouse x-position by 1
I'll try my solution but I have no idea how to do it.
Here's a gif of my problem
Something that might work although idk exactly how to do this is to make the mouse an in game object that moves along with everything else when the screenshakes
That's the problem though, I think. When the camera moves to the right due to the screen shake that also means that my player aims to the right, which is not intended.
Well what Im saying is make the mouse move with the screenshake as well
because the reason the player's aim is wobbly is because the player is moving during screenshake and the mouse is not
So if the mouse moves as well it should be fixed
Wait, think you're on the right track, but it should move the other way from the screen shake offset
Well you wouldn't want it to be opposite because then it will just make the bullets wobble more
Let's say I move the mouse with the camera and just spray, that means my mouse will follow the camera which is shaking, which means that my mouse in turn will shake, which will make my aim shake.
The aim wouldn't shake if both the mouse and player are moving the same amount
but I dont want my character to move, do you mean my camera?
Well yeah I do mean the camera, what I'm trying to say is your mouse isn't affected by the camera but if it was then you wouldn't have wobble
Offsetting the aim seems fine.
Cinemachine has more of a pipeline structure where some stuff is calculated at different times and values are kept track of.
My mouse is affected by the camera though
Whenever my screen shakes my projected mouse position changes
i want to have a certain limit to which if a player passes that limit he respawnscan someone give me a step by step turotial
on how to make the ground move up and down
Why would someone make a step by step tutorial for exactly that
huh
So, @brittle lagoon, you have two questions, right?
- How to make the ground move up and down.
- How to make a player respawn if he travels beyond a certain area.
Correct?
Whats the best way to make a sprite flash white to show damage? I understand the coding aspect, but I dont really know much about materials/shaders or anything like that
Making new sprites that are white and replacing the original sprite with them isnt a great option because there are a lot of animations
@nova coyote are you not just able to change the sprite's color property?
What i settled on was changing the spriteRendered color to red, which works
but the fault color of all sprites is white, so changing it to white just makes it the default color
Why does my player only move right/left once and not continually? Movement is set up so that either pressing A and D keys or pressing two buttons moves the player right/left, but the buttons only move once, even when I turn the voids into Couroutines. Here's my code https://hatebin.com/odpdjfbost
how do i check which position is the player looking
hii i need help
Does anyone have a video tutorial on how to make a gui to dress your character in unity? I need it urgently, I can't find anything to help me on YouTube, my English is very bad, I'm using a translator
I'm having trouble with unity's 2d animator system, i am following a 2d platformer tutorial (from MuddyWolfGames) and although i followed the tutorial exactly, there are no animations playing. After checking the animator tab while running the game, i see that the animations are just not triggering. I am a beginner in all of this and don't really know what information i should be providing rn, so sorry about that
@crystal isle you can activate animation through code by
setting the animation to activate through certain parameters using the unity interface
It's complicated your better off paying a person to help you. Or learning step by step until you know what you're doing.
Your coroutines aren't doing anything.
Is your script on the player?
Cause I used your code it and worked just fine.
how do i check which position is the player looking
local space
relative to global space
thats how you know
if you want a easy way though... you can attach a object to its front
how would i get the difference of one object to its self
i want to get an enemy to always fly to your character
so you know which way its facing @still tendon
distance formula
can i get that
or wait was it distance formula....
its been a while lmao
its enemy position - player position
if its enemy to player
else its player - enemy
'GameObject' does not contain a definition for 'position' and no accessible extension method 'position' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
for this
Vector3 difference = you.position - transform.position;
@coral nest
remove collision from one layer and put them on it
or make them ignore objects that are tagged player
Is there a way to make an object have a randomly chosen texture?
For example I have a rock in my game but I have drawn like 8 different versions and I want each rock to have a randomly chosen one of those versions
Would it just be easier to make 8 different rock objects and randomly choose from them?
@tropic inlet ew you
you probably want [SerializeField] private GameObject death; ;)))
Hello, this code worked for me on other projects, but for some reason, it doesn't work in some cases (and I don't know what's causing the issue.)
This code throws the Null Reference Exception error:
(the error comes from returning the GameObject in the function)
void Update ()
{
if (Input.touchCount > 0)
{
Debug.Log(TouchingObj());
}
}
//Return Touching Object
GameObject TouchingObj()
{
//Shoot ray
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint((Input.GetTouch(0).position)), Vector2.zero);
//Return gameObject
if (hit.transform.gameObject == null) return null;
return hit.transform.gameObject;
}```
Could someone point out what's the problem?
Thank you so much!
Thank you so much!
Could you share how I can fix it?
return hit.transform == null ? null : hit.transform.gameObject;
@rigid juniper are you able to store a texture in a variable of some sort?
I've never done it, but the basic idea could be
[SerializeField]
private Texture[] textures; //set in inspector
private Texture texture;
private void Start(){
texture = textures[Random.Range(0, textures.Length - 1)];
}
Thanks! It worked 🙂
i am trying to get the bullet of the enemy to kill the player but its not working, here is my code
private void OnCollisionEnter2D(Collision2D collision) {
Debug.Log("1");
if(collision.gameObject.CompareTag("Enemy")) {
Debug.Log("2");
Destroy(gameObject);
levelManager.instance.Respawn();
}
Fom that i get a 1 but not a 2
I do have the tag on the bullet and their clones
make sure the tag is uppercase
it is case-sensitive i guess
it is, if you look at the screen shots and code, i think its right
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Death : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision) {
Debug.Log("1");
if(collision.gameObject.CompareTag("Enemy")) {
Debug.Log("2");
Destroy(gameObject);
levelManager.instance.Respawn();
}
}
}
This is on the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class levelManager : MonoBehaviour {
public static levelManager instance;
public Transform respawnPoint;
public GameObject playerPrefab;
private void Awake() {
instance = this;
}
public void Respawn () {
Instantiate(playerPrefab, respawnPoint.position, Quaternion.identity);
}
}
and this one just floats on an empty thing
the destroy should be the last thing it does, or the object will be destroyed and this line won't be called at all:
levelManager.instance.Respawn();