#💻┃code-beginner

1 messages · Page 428 of 1

river quiver
#

i remember tho when i was using an outdated version of unity it was created automatically, like i didnt have to create one

eternal needle
#

Debug.DrawRay

#

To visualize stuff like that cross product or the new direction that you're adding to the position

neon ivy
#

I didn't know that was a thing

languid spire
eternal needle
#

Dont think that joint has a way for it to break like this. You could try to configure its break force through trial and error but I wouldnt. Maybe just delete the joint yourself when it's far enough away

#

Configuring joints are always a pain in the ass imo

remote osprey
#

Isn't there a joint that's more specific to what I need?

#

Also, I agree I don't want to tweak parameters like a monkey all day 🐵

#

Cause I want to make a game where realistic physics is really important

#

So, if I just delete the joint when it's far away without tweaking the velocity/acceleration in a realistic way the game might just not feel as funny to play

eternal needle
# remote osprey Isn't there a joint that's more specific to what I need?

🤷‍♂️ look through the joints and see for yourself if any fit your use case. I vaguely remember from others that 2d joints are way more limited than 3d, you can always make your own. Though I fail to see how you want realism here when you're using a joint for a nail hanging off something

neon ivy
#

@eternal needle welp that literally showed me exactly what was wrong, the result needed to be inversed so *-1 and it's done

#

thanks UnityChanThumbsUp

remote osprey
#

I can't explain everything here without it being hard to understand

#

but it works just like a nail attached to something

eternal needle
eternal needle
#

My answer is still the same, look through the existing joints and see for yourself.

neon ivy
remote osprey
#

I'm literally asking for help so I don't have to go through all of the joints and test every parameter, cause I already went through almost all of them and didn't find anything that helped my problem, otherwise I wouldn't be asking for help here...

quick fractal
#

How would I effectively modify the environment settings and skybox through code? I don't see how I can access the scene 😅

remote osprey
#

You're not being helpful at all with this attitude, @eternal needle

#

Anyway, I'll deal with it myself

#

have a nice week

eternal needle
languid spire
#

someone seems to have a space/ time dislocation problem, today is Wednesday

eternal needle
#

🤷‍♂️ probably just upset that their problem couldnt be directly solved. Which tends to happen if people dont state the actual problem.
First it was breaking a joint after a certain distance, which I answered. That didnt suit their true use case so the solution was dismissed.

eternal needle
remote osprey
#

I already said my problem is exactly like a hanging nail physics (an analogy, my game is NOT nails hanging)

languid spire
eternal needle
#

It would be cutting into the mesh and sticking whatever the nail is, in

remote osprey
remote osprey
remote osprey
#

Do i do this literally and unity would get the physics right?

eternal needle
#

You should definitely reconsider what you're actually doing, because most games will fake everything. I dont think it's really possible to make a "nail in wood" scenario without massive issues

#

Even if you set the friction really high, it's not realistic. If the objects rub against each other itll be sticking almost, while this sticking behaviour was only meant for when the nail was inside.
If you use a joint, theres this sudden magic force pulling the nail back inside which obviously doesnt exist in real life

remote osprey
#

Maybe it's just a matter of simulating physics using vectorial calculus then

#

I didn't want to do that, since its a lot of work, but this seems to be the only way

#

I don't think I'll be able to achieve what I want without making the nail physics, I really need realistic physics to achieve it

#

Anyway, thank you so much for your help!

#

Have a nice week ❤️

zenith crown
proper cloud
#

im trying to change the material on a TextMeshProUGUI via code but cant seem to do it. Google also doesnt seem to have a good answer.

public TextMeshProUGUI costText;
public Material costMetTxt;
public Material costNotMetTxt;

public void SetCostText(bool costMet)
{
    costText.material = costMet ? costMetTxt : costNotMetTxt;
}

this seems like the most straightforward way to do it, but it visually does nothing

winter tinsel
#

question, is setting the timescale to 0 the best way to pause a game? what if i make a main menu , should it just overlay the game or be in a different scene untill i press play and it makes the timescale 1 again?

zenith crown
winter tinsel
#

huh?

#

by main menu i mean start menu, the one before the game

zenith crown
#

Start menu before you actually start playing should be a seperate scene

winter tinsel
#

aha

#

how do i make it the main scene

#

the starting one ig

zenith crown
#

I havent got that far im still a beginner 🙂

winter tinsel
#

lol

#

thanks for the help

languid spire
#

make sure it is the first one in the build settings, the one with an index of 0

winter tinsel
#

if im on the main menu scene it wont load the actual game scene right?

queen adder
winter tinsel
#

itll stay unactivated ig

queen adder
winter tinsel
#

okay

#

so if one is loaded the others wont be

queen adder
#

yes (Theres probably a way to have multiple for like separate physics calculations but thats a whole other thing)

winter tinsel
#

you said usually so how can there be more than one running at a time?

winter tinsel
#

another question

#

what if

#

i had a character with an inventory

#

moving from one scene to another

#

how would i make it so that the contents of his inventory stay the same ?

queen adder
#

use DontDestroyOnLoad(), but saving it into like a file would be good (A ScriptableObject perhaps)

proper cloud
queen adder
# winter tinsel what does that method do

When a new scene is loaded, all the object in the scene get destroyed, and all the objects from the new scene spawn, DontDestroyOnLoad prevents an object from getting destroyed each time a new scene is loaded

winter tinsel
#

im guessing i put the gameobject in the brackets right?

winter tinsel
#

okay

rare basin
#
public void SpawnAndFireBullets()
{
    StartCoroutine(StartSpawning());
}

private IEnumerator StartSpawning()
{
    foreach (var point in spawnPoints)
    {
        var playerPosition = PlayerManager.Instance.player.transform.position;
        var offsetedPosition = playerPosition + Random.insideUnitSphere * 3;

        var directionToOffsetedPosition = (offsetedPosition - point.position).normalized;

        var projectile = BGPoolManager.Instance.GetFromPool(ObjectType.ZSOLTAR_RIFLE_PROJECTILE);
        projectile.transform.position = point.transform.position;
        projectile.transform.forward = directionToOffsetedPosition;

        if (projectile && projectile.TryGetComponent(out ExplodeProjectileBullet bullet))
        {
            Debug.Log("Time Scale: " + Time.timeScale);
            Debug.Log("shooting bullet");
            bullet.StartCoroutine(bullet.ShootBullet(directionToOffsetedPosition));
            yield return new WaitForSeconds(delayBeetwenEachSpawn);
            Debug.Log("after wait for seconds");
        }
    }
}

I have a function SpawnAndFireBullets() that I am hooking in UnityEvent that is starting a coroutine, althought it fires only one bullet and gets stuck at WaitForSeconds. The Debug.Log after wait for seconds isn't printed. The game object is not being destroyed, time scale is 1, what am i doing wrong. Delay between each spawn is 0.3f

zenith crown
queen adder
zenith crown
#

yes

queen adder
#

oh wait youre talking about the crouching?

zenith crown
#

Yes

#

theres frames where its thru the ground

queen adder
#

That makes sense because youre just setting the new size right away, without any calculations to bring the player up a little

zenith crown
#

Oh no i have to bring him down a little for it to work

cinder crag
#

im having a bit of a problem , so i have a chargeable bow which depending on how long you charged it for , it will deal that much dmg etc but im not sure on how to mkae only the bows dmg to change and not the others since seems like when i use my bow and yk i shoot the enemies , then go buy the pistol from the shop , it only deals 1 dmg so im asking on how to make it so only the bow can have that dmg since i have a SO that handles the firerate , dmg etc and in second ss it shows that im putting the weaponSO.DMG = ArrowDMG which is why the dmg gets changed as well , im not sure on how to make it so only the bow has that dmg

queen adder
queen adder
zenith crown
#

Like here

queen adder
#

Well you can also change the transform position directly, I dont know the best approach though
Maybe lerp the height so he doing go through the ground too much

zenith crown
#

Yeah i was gonna add lerping into everything a bit later on to smoothen it out but atm i want the base to work flawlessly

zenith crown
#

😂

queen adder
eternal needle
rare basin
zenith crown
queen adder
zenith crown
#

I only change the Y position

#

i can show you

#

Thats how i do it

sand heath
atomic holly
#

Hi
To save some data when I change scene, I create a Prefab that call before all scenes. Do I put my main camera and my player gameobject in this prefab or just some data like inventory ?

sand heath
#

It can be a static class

eternal needle
sand heath
#

There are tutorials for save systems if you're curious on how to make one

atomic holly
ivory bobcat
eternal needle
#

im sure people do lots of things, but saving data in a prefab is probably the worst

wanton pecan
#

.fm

atomic holly
#

So you advice to do the system of do a prescene at first with DDOL ?

wanton pecan
#

Oh wrong server

sand heath
#

You could also just make a script that specifically does that though, or use OnGUI etc

eternal needle
sand heath
#

The player can also hold its own data and persist between scenes

eternal needle
queen adder
atomic holly
#

But is it better to put in all scenes the prefab of the player and the main camera or try to save it in DDOL ?

sand heath
#

(I'm lost on what DDOL means I've never heard this term?)

eternal needle
#

Usually you dont wanna put your player in every single scene, as you can just spawn it at runtime

eternal needle
sand heath
#

Ohhh FacepalmNatsuki I just woke up mb

atomic holly
#

Okay thanks guys, I'll see how do these many things

sand heath
atomic holly
eternal needle
#

well i dont know if you think i answered your question, i was trying to get more clarification so i could answer it properly. But if you feel you know what to do now then carry on

zenith crown
atomic holly
sand heath
cinder crag
atomic holly
#

And also teleport the player to a specific position after load the new scene

sand heath
atomic holly
#

Yes

#

But for this, I know how to do to save data in JSON

sand heath
#

OK so you understand serialization and how to save/load to a data class?

#

Serialization**

#

Lmao

atomic holly
#

But I want to save data in JSON only in some locations and not always between scenes

sand heath
#

As in you don't want saving tied to scene change?

#

When are you wanting to save then

atomic holly
atomic holly
languid spire
atomic holly
sand heath
#

Its only necessary to load the save data once when bdginning, then you can make the player DDOL.

#

The player can then use a spawn manager to get "spawned" at where it should be on the next scene

atomic holly
atomic holly
sand heath
#

Would be preferred, a main menu basically

atomic holly
#

In a gameobject of the actual scene or the future scene ?

sand heath
#

You could also make each individual scene load the save data redundantly (or check if the data == null and load data if it hasn't been loaded yet)

atomic holly
#

And save it again when he'll move to a new scene ?

sand heath
sand heath
atomic holly
sand heath
#

I'd make a seperate spawn point object personally

atomic holly
sand heath
#

Then you request a spawnpoint from the spawn manager as the player when you enter the scene

sand heath
#

No point in reloading save data between scenes

atomic holly
atomic holly
#

So you'd do that to an Update() function or Start() ?

sand heath
#

Player.cs

OnSceneChange:
Find the spawn manager
Transform.Position = spawnmanager.getspawnpoint()

Spawnmanager.cs:
Return spawnpoint.transform.Position

atomic holly
sand heath
# atomic holly So with OnSceneLoaded ?
    void Start()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    // called second
    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        var spawnManager = // find the spawn manager somehow (singleton, findanyobjectoftype, gameobject.find, etc..)
        transform.position = spawnManager.GetSpawnpoint();
    }
eager spindle
#

today I learned that SceneManager has that

atomic holly
#

what are the parameters of OnSceneLoaded for ?

eager spindle
#

Scene scene is just the scene that is loaded, LoadSceneMode tells you if the scene is loaded single or additively.

In this case it doesn't matter here, you just want to do something when the scene is loaded

sand heath
sand heath
atomic holly
#

So you put this in the player script right ?

naive lion
#

Using Cinemachine 3, should i reference the main camera (with brain) or the CinemachineCamera to perform fov operations?

sand heath
round plover
#

anybody know why when my cube falls it doesnt rotate? it stays still

frosty hound
#

Why are you expecting it to rotate? Are you actually putting any force on it that would cause it to?

round plover
#

i mean i dont rerally think it matters tbh

sand heath
#

well having 0 angular drag would make it pretty unlikely to rotate wouldnt it

#

its also a cube falling straight down

#

unless something pushes it, there's no reason it would rotate

round plover
#

its fine i just thought it should have been rotating if falling but my end result i want it still so it doesnt matter to much anyway

sand heath
#

physics isn't my strong suit 😅

round plover
#

bruh lol

sand heath
sand heath
#

well i was right in the wrong kind of way

round plover
tough phoenix
#

im selecting a random element from an array but i need to check if there is an item in it
if there is, it needs to select another element
what is the best way to do this

cosmic quail
#

have a list of slots that have an item in them? and select from that one

random dove
#

I dont know where to ask this question sorry if wrong. How To Make "Enemy for fps shooting game" he just follow me and shoot at me.

#

i wanna know basics of ai, nav mesh etc.

ivory bobcat
#

If you rearrange the null elements to the end of the list, you could set your random selection to indices in the array that would contain actual elements.

tough phoenix
#

i changed my code, thanks @ivory bobcat @cosmic quail

tough phoenix
cinder crag
eager spindle
# random dove I dont know where to ask this question sorry if wrong. How To Make "Enemy for fp...

break the problem down into multiple parts

  • enemy
  • having enemy follow you
  • having enemy shoot at you

start by creating an enemy with their collider and model. make a new script called Enemy AI, attach it to the enemy.
in the script, under update, you may raycast between the enemy's head and player's head. if there's no object in the way, the enemy has seen the player and can start moving towards the player. to keep track of if the enemy has seen the player you can look into a Finite State machine.

for now dont take pathfinding into consideration, just move the enemy position to the player first and make the enemy shoot in the direction of the player.

once you have all the basics down you can substitute the code for navmesh pathfinding. Unity has a package for it already, this is something you shoul research by yourself seperate from the enemy code. once youre familiar with navmesh, one way to go about it is changing the target gameobject based on whether the enemy has seen the player.

eager spindle
#

ask more concise questions

eager spindle
#

everything will click once you play around with it enough

ivory bobcat
cinder crag
eager spindle
#

as in

#

i dont understand what you've typed in that message

#

you only want to change the bow's damage but not the gun's damage?

#

why arent the bow and guns from different scriptable objects?

cinder crag
cinder crag
summer stump
#

Well, you would have individual SOs for each weapon type, and then do not change their values at runtime at all. The mutable data should be store in a class, while only the defaults are in the SO

cinder crag
summer stump
cinder crag
summer stump
#

Bow should have its own asset

cinder crag
#

I alr have them dwdw

summer stump
#

This will create an asset instance from the WeaponSO

cinder crag
#

For both Bow and Pistol

summer stump
#

Ok perfect. Then changing that instance will NOT affect any other weapon

cinder crag
summer stump
#

You want to change them in the inspector

cinder crag
#

I kinda need to do it in code lol

summer stump
#

Just use a POCO

cinder crag
#

What's an POCO

summer stump
#

A plain class

polar acorn
#

A class that doesn't extend anything

#

its entire purpose is to pass data around and have instances and that's it

summer stump
#

Because you are doing the one thing I said not to do, which is change the values at runtime

summer stump
polar acorn
#

that's the point of it

#

It's a data structure that you make

cinder crag
#

So I just make a class and put all the data I need in there then use it for when I'm trying to change a weapons DMG?

summer stump
#

Yes

round plover
#

have a problem when my cube hits the obstacle my cubes movement is supposed to stop slighlty but it keeps going

stiff birch
round plover
#

it dis

#

dis

#

did

cinder crag
# summer stump Yes

So what I'm understanding

• have a class that holds the different data I need
• use the DMG field when changing a weapons DMG
• I don't need a SO for the data or I need it

Sorry I'm trying my best to understand atwhatcost

polar acorn
round plover
#

when it hit obstacle it printed

#

maybe its unity not my code

polar acorn
stiff birch
#

the one you're trying to disable

round plover
#

ok

stiff birch
#

Nah, i mean the code

round plover
#

when it hits obstacle i want it to turn off and slow down

#

ohh

polar acorn
# round plover

Okay, so, if this log is inside the if condition, then whichever playermovement1 you are referencing in the movement variable gets disabled

cinder crag
polar acorn
#

If you're not seeing it be disabled, then either:
A) Something else is enabling it
B) movement is not the one you think it is

stiff birch
#

You probably set a velocity to your rigibody, hence, disabling the script won't stop your player

polar acorn
storm imp
#

how do I fix this error?

polar acorn
#

You do not want to change any data in an SO at runtime

polar acorn
round plover
#

it just keeps movinmg

#

moving

#

but i want it to slow down and stop

#

after i ran it

polar acorn
upper tide
#

Is there a way to check if a meshrenderer has a certain material? I've tried checking meshRenderer.material but since it returns an instance I can't compare it to the material I've assigned in editor

summer stump
storm imp
summer stump
eternal falconBOT
polar acorn
eternal falconBOT
polar acorn
#

DOUBLE KILL

cinder crag
storm imp
summer stump
#

Pretty sure you have been told to configure your ide many times maryo

summer stump
polar acorn
cinder crag
cinder crag
raw token
storm imp
cinder crag
#

My brain is expanding notlikethis

upper tide
summer stump
storm imp
#

I have configured it I see the things online in red now I didn't have to do anything

cinder crag
raw token
muted narwhal
#
                _itemGameObject = new GameObject
                {
                    transform =
                    {
                        position = Vector3.zero,
                        parent = transform
                    }
                };

Why isn't it working? It supposed to set the position of a freshly created game object to zeros, but... it doesn't

winter tinsel
#

something definitely feels off here

raw token
winter tinsel
#

ive never encountered something like that

polar acorn
polar acorn
muted narwhal
#

it's called object initializer

winter tinsel
#

also does transform even work with curly brackets?

#

is that a thing??

languid spire
#

it wont, transform within transform

polar acorn
#

So, no, this isn't a valid object initializer

storm imp
#

I don't know how to fix it

muted narwhal
#

it is creating, but the position isn't setting

polar acorn
#

but not a Transform

raw token
upper tide
#

Thank you!

muted narwhal
#

Well, how can I fix it then?

polar acorn
muted narwhal
#

Literally the same result

polar acorn
storm imp
#

the 3 blue are connected how do I disconnect them?

muted narwhal
#

It supposed to set the position of a freshly created game object to zeros, but... it doesn't

muted narwhal
#

Set it's to some randomly coordinates, somewhere in the screen's edge

rich adder
muted narwhal
#

that's definetly not zeros

storm imp
rich adder
polar acorn
storm imp
rich adder
#

huh..what happens when you right click it

muted narwhal
summer stump
# storm imp

What do you mean they are connected to each other?

muted narwhal
#

Thank you

storm imp
rich adder
storm imp
rich adder
#

if they share a material of course they change all three

summer stump
storm imp
polar acorn
storm imp
storm imp
rich adder
storm imp
polar acorn
#

You drag a material onto one of the objects, and that is the object that changes

storm imp
storm imp
storm imp
# polar acorn ...they do?

The sphere for outside cross changes material but when I drag a material over onto under cross it doesn't change the sphere

coral tiger
#

!code

eternal falconBOT
polar acorn
#

Then you click on Under Cross and it has the Under Cross Material

#

So what are you expecting to happen

storm imp
polar acorn
#

you can literally see them changing in the video you sent

#

I don't know what you're talking about

storm imp
#

Yes but the sphere on the left is not visually changing

polar acorn
storm imp
polar acorn
storm imp
#

leaves

polar acorn
# storm imp leaves

Are you sure, because in your video it changes when you change the material on under cross

#

Sorry, outside cross

coral tiger
#

Complete noob to C# here.

Is there a reason when creating my variable '''cs Public bool birdIsAlive = true''' it dsoen't actually set the boolean to true?

storm imp
polar acorn
polar acorn
#

The stuff you're saying isn't happening is happening just fine

#

Three spheres, all with their own materials. Changing one has no affect on the other two

#

the one you can see in the scene view is visibly updating when you change its material

#

I don't know what to tell you. You appear to be hallucinating problems, because your video shows it working exactly as you said you want it to

storm imp
queen adder
#

How do I make an object show and not show?

languid spire
queen adder
willow scroll
#

Hey. What way to get files inside of the Editor script without serialization would you recommend me? Putting suitable files into the Assets/Resources folder?

wintry quarry
willow scroll
atomic holly
#

Hi,
I do a prescene to add all objects will be DontDestroyOnLoad with this script :

using UnityEngine;
using UnityEngine.SceneManagement;

public class DontDestroyOnLoad : MonoBehaviour
{
    public GameObject[] objects;
    
    private void Awake()
    {
        foreach (var element in objects)
        {
            DontDestroyOnLoad(element);
        }
    }

    private void Start()
    {
        Debug.Log("DDOL activated");
        SceneManager.LoadScene("Scene01");
    }
}

But when I press play, I'm in the scene01 but my objects in DDOL are desactivated. Why ?

wintry quarry
wintry quarry
queen adder
willow scroll
spiral glen
#

if I get an error saying object reference not set to instance of an object, that just means the object I'm attempting to reference isn't being understood right?

polar acorn
polar acorn
wintry quarry
spiral glen
#

oh ok

languid spire
wintry quarry
spiral glen
#

I fixewd it

#

for some reason it un-added my object from the script

#

so it left the referenced script as null instead of as what it should of been

#

should of looked more closely mb

atomic holly
#

I have just this in the prescene

coral tiger
# polar acorn It sets that variables _default value_ to true. If you change it in the inspecto...

Sorry, as mentioned complete novice, just trying to understand why it works this way.

I see the variable in the inspector and can check or uncheck the box,. But when I first made the script for the first time and set the value to = true, it didn't until I added //myBool = true inside of the Start() function.
Like all my other variables (int/float/str) show the default value I set when they were created before changing them elsewhere in the script or in the inspector. But boolean seems to always start as false unless I set it to true in the start() or update() functions. Is that just a quirk of C#?

wintry quarry
#

It could be anywhere

#

Wait also are those prefabs?

atomic holly
#

Is it a problem ?

wintry quarry
summer stump
wintry quarry
atomic holly
wintry quarry
#

you would need to instantiate them, then call DDOL on the instances

wintry quarry
#

they are just assets

#

if you want them in the game world you need to Instantiate them

coral tiger
summer stump
#

It will do whatever the code says AS LONG AS the inspector is not overriding it

raw token
atomic holly
#

Thanks !

summer stump
coral tiger
raw token
summer stump
queen adder
# languid spire you can use gameObject.SetActive

Why does this not work?

if (Input.GetKeyUp(KeyCode.V)) { isShopShown = !isShopShown; }

    if (isShopShown == false) 
    {
    ShopCanvas.SetActive(false);
    }

    if (ShopCanvas == true) 
    {
    ShopCanvas.SetActive(true);
    }
languid spire
#

if (ShopCanvas == true) ?

wintry quarry
#

why not just ShopCanvas.SetActive(isShopShown);?

languid spire
#

pay attention

coral tiger
languid spire
queen adder
#

I just did what thought made sense im brand new

#

not brand new but a few weeks

#

Why does this not work

if(Input.GetKeyUp(KeyCode.Escape))
{
ShopCanvas.SetActive(isShopShown);
isShopShown = !isShopShown;
}

queen adder
languid spire
#

is this code on ShopCanvas?

queen adder
#

yes

polar acorn
languid spire
#

code does not run when an object is de activated

queen adder
#

Im a little silly well only one way to learn

#

easiest fix of my life thanks!

languid spire
languid spire
#

also activate/deactivate a gameobject is much more expensive than enabling/disabling a component

queen adder
languid spire
#

that's not the only thing but it is the most important

queen adder
#

Im not too worried becuase im just making a small project to learn the basics

languid spire
#

but it never hurts to learn best practices. In game dev always endeavour to do the least amount of changes to achieve the effect you want

queen adder
#

100% agree I should be doing that and that sounds right wanan save time

dusty ember
#

Does anyone know how to make my game less pixelated

wintry quarry
dusty ember
#

scale is on the least it can be

wintry quarry
#

beyond that, turn on anti-aliasing.

dusty ember
wintry quarry
dusty ember
#

yeah 1.3x

wintry quarry
summer stump
steep rose
#

better in unity talk, yes?

simple mural
#

Heyo can anyone in here help me with an issue im having in unity?:)

#

Im trying to reference a class in another script, but for some reason i cant figure out why it wont let me

rocky canyon
#

which class to which class?

#

send example code / screenshots

simple mural
#

Im very new so im unsure.

Im trying to use Addresource in the shopbutton script

#

Idk if i've given enough context

rocky canyon
#

so it looks like u made a singleton from ur ResourceManager called instance

#

ResourceManager.instance would be how u access it

#

like u have there in ur ShopButton

wintry quarry
#

what happens when you try?

rocky canyon
simple mural
#

In the other script where i wrote the same thing it turned green, but i am getting this error

wintry quarry
rocky canyon
#

ohh thats b/c Button is in the UI namespace i beliieve

wintry quarry
#

you're just mssing using UnityEngine.UI;

rocky canyon
#

using UnityEngine.UI;

simple mural
#

Now i get this one

wintry quarry
simple mural
wintry quarry
#

Also the fact that your code editor is not highltighting these in red and not autocorrecting means your IDE is not configured properly

rocky canyon
wintry quarry
#

you should stop what you're doingn and get it configured

rocky canyon
#

!ide

eternal falconBOT
rocky canyon
#

powpow

wanton kraken
#

the following code is supposed to ensure on that on powerup pickup, the gameobject that's selected to be added to inventory isn't already there. inventory is an array of 3 (0,1,2) called Bullets. any ideas on why this won't work?

    public GameObject RandomRoll()
    {
        List<GameObject> possibleBullets = new List<GameObject> {BouncingBullet, DoubleDMGBullet, PassThroughBullet};
        foreach (GameObject bullet in Bullets)
        {
            possibleBullets.Remove(bullet);
        }
        if (possibleBullets.Count > 0)
        {
            int roll = Random.Range(0, possibleBullets.Count);
            return possibleBullets[roll];
        }
        return NoBullet;
    }
eternal needle
wanton kraken
#

doesn't seem like any of them are happening?

eager spindle
#

if you're using visual studio you should use the debugger, the big green button on top

#

check the value of possibleBullets

wanton kraken
#

i'll try that.

wintry quarry
wanton kraken
#

it doesn't seem to sort anything, just picks a random bullet.

eager spindle
#

the bullets arent being removed

#

my theory is that the variable in a foreach loop isnt the same as in a for loop

#

could you replace foreach with for loop instead?

wanton kraken
#

i'll give that a shot

wintry quarry
#

your code just picks a random bullet

#

No sorting here:

       if (possibleBullets.Count > 0)
        {
            int roll = Random.Range(0, possibleBullets.Count);
            return possibleBullets[roll];
        }```
eager spindle
#

more of filtering out stuff

wanton kraken
#

?? it makes a list of possible bullets, and is supposed to pick from that. possible bullets shouldn't include bullets that are already in the inventory

polar acorn
wintry quarry
#

it's picking one that's already in the inventory?

languid spire
#

almost certainly possibleBullets is being populated with prefabs not instantiated gameobjects

wintry quarry
#

I mean - wouldn't prefabs make sense here?

wanton kraken
#

hold on a moment guys, i have an idea. let me try it quickly

#

and yes, it is prefabs

languid spire
#

no prefab != gameObject

polar acorn
wintry quarry
#

prefabs are definitely GameObjects, but yeah we have no idea how Bullets is populated. This question is devoid of a lot of context

#

including what is actually going wrong/happening

languid spire
hollow forum
#

how do i actually move an object with transform and a Vector2

#
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using JetBrains.Annotations;
using UnityEditor.Callbacks;
using UnityEngine;

public class Movement : MonoBehaviour
{
    // Start is called before the first frame update
    
    public GameObject Planet1;
    public GameObject Planet2;
    public Rigidbody2D rb1;
    public Rigidbody2D rb2;
    public static float initialveloctity;
    public Vector2 velocity = new Vector2(0, 0);
    public Vector2 initial = new Vector2(0, 8);
    public Vector2 acceleration;
    public Vector2 force;
    public Vector2 displacement;
    public float displacementMagnitude;
    public float GravitationalConstant = 0.05f;
    public Vector2 position = new Vector2(0, 0);
    
    
    void Start()
    {
        Vector2 position = new Vector2(Planet1.transform.position.x, Planet1.transform.position.y);
    }

    // Update is called once per frame
    void Update()   
    {
        displacement = Planet1.transform.position - Planet2.transform.position;
        displacementMagnitude = displacement.magnitude;

        Vector2 velocity = new Vector2(0, 8);
        
        Vector2 force = displacement.normalized*(GravitationalConstant * rb1.mass * rb2.mass) / (displacement * displacement);

        Vector2 acceleration = force/rb1.mass;

        velocity += acceleration * Time.deltaTime;

    }

}
#

everything i try throws an error

rocky canyon
#

well, whats the error

cosmic dagger
#

bcuz there are tons of tutorials for this . . .

hollow forum
#

cs1612 cannot modify as it is not a variable of the gameobject

cosmic dagger
#

post the actual error message. that doesn't tell us enough . . .

#

we don't know what you're trying to modify . . .

hollow forum
#

another line at the bottom

#

to try to change the position

tidal kiln
#

make a new vector

cosmic dagger
pulsar forum
# hollow forum

Technically you can do this(I mean in a fundamental sense you can change your copy) it just won’t be applied your transform

tidal kiln
#
var newPosition = Planet1.transform.position;
newPosition.x += velocity;
Planet1.transform.position = newPosition;
hollow forum
#

public Vector2 position = new Vector2(Planet1.transform.position.x, Planet1.transform.position.y);

#

ive done this

#

but it meant that my planet1 gameobject needed to be static

cosmic dagger
cinder crag
# summer stump The second sounds better

https://paste.ofcode.org/39FxtaFSUvKEGZMQshJMYKw (weaponShooting script)

okay so i did make a new class inside the WeaponShooting script and referenced that new class in the WeaponShooting class then set the WeaponSO.name\DMG\fireRate to WeaponStats in the SetPOCODataToSOData() method then call that method in update but the pistol still does the same dmg as the bow when it last hit so if the bow was charged and dealt like 3 dmg then the pistol does the same dmg as well but it supposed to deal 15 and im not sure on how to fix it

hollow forum
#

which i am trying to eliminate by removing all instances of Planet1

cosmic dagger
# hollow forum

you cannot modify a single axis of position because it's a Vector3 (struct) and returns a copy of the position. that's why you need to create a temporary variable, modify that, then assign it back . . .

hollow forum
#

idk why i did that lmao

cosmic dagger
summer stump
#

You are setting the SO data in code at runtime

You set the POCO data to what your SO has.

Again, do not change the SO via code at runtime

You want WeaponStats.name = WeaponSO.name

zenith crown
#

Anyone here that used a character controller and made a crouching script for it? Im having trouble with mine and would like to take a look at others solutions

steep rose
#

its easy to crouch, just scale your player down by an amount you prefer and have a custom movespeed for crouching, you could also make it so you cant jump if you want

#

i personally dont use character controllers that much but it is what it is, we can help you with your crouch problems if you present code for us

zenith crown
#

give me a second to present it fully

steep rose
#

for sure 👍

summer stump
cinder crag
#

also seems like it didnt really fix anything

hollow forum
#

now getting this error

#

i donht understand why it sayts my input position on y axis is infinity or undefined

zenith crown
#

Thats both when crouching and crawling

hollow forum
#

yes but ive got displacement.magnitude squared

#

and there is a difference on x axis

#

so im not sure why its giving that cause surely the magnitude should just be 22

polar acorn
#

Either displacement.magnitude is 0, or rb1.mass is zero

steep rose
zenith crown
#

No worries take ur time

hollow forum
#

rb1.mass is zero

#

and i cant console it cause it just wont run

#

but they are seperated

#

so there should be a displacement magnitude

polar acorn
#

When you add NaN to a valid number, that number becomes NaN

steep rose
zenith crown
#

Oh no that i was gonna do after

#

dont worry about that

#

currently the hitbox is all over the place (video)

cinder crag
hollow forum
polar acorn
zenith crown
hollow forum
#

the mass isnt zero tho

#

its 0.01

polar acorn
#

Why did you just tell me it's zero

hollow forum
#

i meant to say it isnt

ashen sonnet
#

guys if i use a boxcast to detect if the player is onground, wouldnt that mean that if the player just jumped the exact frame before hitting the ground, they would jump slightly higher? because the boxcast sticks out slightly detecting the player is on the ground JUST before they are?

polar acorn
eternal falconBOT
hollow forum
#
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using JetBrains.Annotations;
using UnityEditor.Callbacks;
using UnityEngine;

public class Movement : MonoBehaviour
{
    // Start is called before the first frame update
    
    public GameObject Planet1;
    public GameObject Planet2;
    public Rigidbody2D rb1;
    public Rigidbody2D rb2;
    public static float initialveloctity;
    public Vector2 velocity = new Vector2(0, 0);
    public Vector2 initial = new Vector2(0, 8);
    public Vector2 acceleration;
    public Vector2 force;
    public Vector2 displacement;
    public float displacementMagnitude;
    public float GravitationalConstant = 0.05f;
    public Vector2 position = new Vector2(0, 0);
    
    
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()   
    {
        displacement = Planet1.transform.position - Planet2.transform.position;
        displacementMagnitude = displacement.magnitude;

        Vector2 velocity = new Vector2(0, 8);
        
        Vector2 force = displacement.normalized*(GravitationalConstant * rb1.mass * rb2.mass) / (displacement.magnitude * displacement.magnitude);

        Vector2 acceleration = force/rb1.mass;

        velocity += acceleration * Time.deltaTime;

        position += velocity;
    

        Planet1.transform.position = new Vector3(position.x, position.y, 0f);

         

    }

}
zenith crown
#

Pls use one of the links CSD

rocky canyon
#

any bigger than that u might wanna use an external paste-bin

zenith crown
#

so it doesnt take up the whole thing

ashen sonnet
# polar acorn Make a smaller box

well yeah but even if the box just stuck out 1 pixel below the player it would still be a problem just to a way way way way smaller degree right? (bro i said frame instead of pixel am i high wtf)

steep rose
hollow forum
zenith crown
#

should solve it

#

or atleast that u cant jump

#

like a temporary stun

polar acorn
# hollow forum ```using System; using System.Collections; using System.Collections.Generic; usi...
void Update()   
    {
        displacement = Planet1.transform.position - Planet2.transform.position;
        displacementMagnitude = displacement.magnitude;
    Debug.Log($"DisplacementMagnitude: {displacementMagnitude}");      
        Vector2 force = displacement.normalized*(GravitationalConstant * rb1.mass * rb2.mass) / (displacement.magnitude * displacement.magnitude);
    Debug.Log($"force: {force}");

        Vector2 acceleration = force/rb1.mass;
    Debug.Log($"acceleration: {acceleration}");
        
        Vector2 velocity = new Vector2(0, 8);  
        velocity += acceleration * Time.deltaTime;
        position += velocity;
        Debug.Log($"position: {position}");

        Planet1.transform.position = new Vector3(position.x, position.y, 0f);
    }

Replace your function with this one

polar acorn
zenith crown
#

without it the smaller hitbox simply stays in air

steep rose
queen adder
#

How do I make calculations in a script

steep rose
#

this is most likely your problem

polar acorn
steep rose
queen adder
ashen sonnet
polar acorn
steep rose
#

if you are worried about a pixel difference couldn't you just apply a tiny force down for a second to negate it?

ashen sonnet
zenith crown
#

a lerp will fix that

#

so i dont find that as an issue

#

but the jumping part is one

cinder crag
polar acorn
ashen sonnet
#

can someone please explain in an almost annoying amount of detail, why everthing in this line works/what it does?

rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
polar acorn
#

That's the least vague answer I can give with how vague the question is

zenith crown
#

Nvm got it solved now

#

the controller skin was stuck in the ground

#

solution was to make the character drop a little bit on the ground

steep rose
ashen sonnet
polar acorn
steep rose
#

correct me if im wrong

steep rose
zenith crown
ashen sonnet
languid spire
steep rose
obsidian shoal
#

im demotivated because i feel im not learning and unity learn is slow

frosty hound
#

Longer than the 10 minute Youtube meme video that made it look so easy at the very least

obsidian shoal
languid spire
obsidian shoal
#

been working 5h a day

rocky canyon
cosmic dagger
ashen sonnet
# zenith crown I can explain the first bit, i dont know what the second bit does tho. AddForce ...

so rb.AddForce is just a thing that moves something with the physics engine specifically, then makes a vector to determine how/where it moves
so this is obv just for my jumping but should i be using this for my movement too? rn im using just like transform.position += Vector3.right * speed *Time.deltaTime
and yeah i still have no clue what forcemode2d.impulse means (time to google it/ask chatgpt)

polar acorn
rocky canyon
obsidian shoal
#

how do i learn faster

ashen sonnet
obsidian shoal
#

i hate watching 1h of videos

polar acorn
#

you learn longer

languid spire
zenith crown
#

dont worry

zenith crown
#

its a part of the process

rich adder
steep rose
#

it would default to forcemode.force

cosmic dagger
obsidian shoal
ashen sonnet
# obsidian shoal i hate watching 1h of videos

watch the GMTK flappy bird tutorial, follow along, then once you're done get an idea for something else to add, and research how to add it (chatgpt or google or whatever), then when u have code that works, learn WHY it works

zenith crown
obsidian shoal
#

what is a diffrent way i can learn other then videos

rocky canyon
#

i tend to jump around projects.. just to make something

#

then i have my main project that i go back and forth too..

#

(the tedious one)

polar acorn
rocky canyon
#

💯 couldnta said it better myself

steep rose
#

with several attemps and many fails and a lot of help from here i got most of my movement code done, so it does take time to get better

obsidian shoal
#

i want to make something myself without a tut but i feel i dont know enough

cinder crag
# obsidian shoal i hate watching 1h of videos

you cant really expect to learn something from a 10 min "how to easily make games in unity" video , it takes lots of practice and time to learn and get to where a expert unity developer is but the experience is painful but fun to learn , you just kinda need problem solving skills and a bit of determination and you should be able to atleast get to a beginner level , for a expert level you have to practice more and more yk

zenith crown
rocky canyon
cosmic dagger
polar acorn
#

They don't need to do well

#

but just do things

#

Learn how to solve problems that come up because that's all programming is

rocky canyon
#

do things frequently... do things well sparingly.. 😄

polar acorn
#

a series of encountering a problem and then finding out how to solve it

cinder crag
rocky canyon
obsidian shoal
#

coming from a 2d dev to a 3d dev its hard to come up with ideas

ashen sonnet
# obsidian shoal i want to make something myself without a tut but i feel i dont know enough

like i said, what a short tutorial to understand VERY fundamentals, like the gmtk flappy bird one, then just make stuff with google and stuff
also if everything is still to confusing, try learning something like python first, cuz python is bassically just english but weirder, and it teaches concepts of programming in a very accessible way so you dont have to worry about where to put punctuation ect

cinder crag
rocky canyon
polar acorn
#

Programming is just "Googling, with purpose"

rocky canyon
#

i dont agree w/ the learning python to learn unity bit

languid spire
#

Speaking as the old, wise man, motivation comes from enjoyment, the more you enjoy game dev the more motivated you will be

steep rose
zenith crown
steep rose
#

lmao

ashen sonnet
rocky canyon
radiant frigate
#

hi! i´ve been runing into a problem, i want to make a triple shot, but i dont know how to offset the other 2 bullets, i have tried everything from; multiplying vectors and quaternions, using radians, degrees, etc, pretty sure one of them would work but i dont think im writting the code i need correctly

zenith crown
cinder crag
ripe shard
#

If you use Python to learn programming you will betray yourself and never really understand it. The best way to learn programming is via C, second best is Java/C#

ashen sonnet
rocky canyon
#

if ur coming from 2D going to 3D then i would recommend

#

2.5D

#

fun fun

steep rose
polar acorn
zenith crown
ripe shard
rocky canyon
polar acorn
steep rose
#

but hard

radiant frigate
#

!code

eternal falconBOT
cinder crag
radiant frigate
languid spire
ripe shard
# steep rose but hard

You can only ever learn coding once. If you learn it through C you get the best start.

radiant frigate
rich adder
#

learning C just to get into c# is not really worth the trouble

zenith crown
#

For me coding was simply translating thoughts into something my pc could read

polar acorn
rocky canyon
steep rose
rocky canyon
ashen sonnet
# polar acorn The fundamentals of programming don't get easier when you do them in a different...

i think python is good for teaching extreme basics of how programming works, conceptually
not how to write code
like i said, python is bassically just english with extra steps, most python scrips when read out loud can be vaguely understood, which makes it very accessible and comprehendible so while it would be more worth your time to learn a more complex language first, if its too hard python could work

cosmic dagger
# obsidian shoal coming from a 2d dev to a 3d dev its hard to come up with ideas

recreate very simple games. challenge yourself to replicate their mechanics and gameplay, then add your own systems/mechanics on top of their game. that will show you can create games by following a provided documentation (the replication) and expand on those ideas by implementing new mechanics (your creativity/expression)

there are simple "clone" games we usually provide: flappy bird, asteroids, galaga, brick breaker, single 2d-mario level, 2d/3d infinite runner . . .

radiant frigate
ripe shard
rocky canyon
ripe shard
#

Python is only used in academia for learning because there they don’t care about actually running code in real hardware.

steep rose
#

only the pros code with linux command line

rocky canyon
#

results may vary imo

steep rose
#

facts

polar acorn
zenith crown
#

i think any language is good as almost all languages rely on the same things just worded differently

radiant frigate
#

i want them to be offset for an exact amount of degrees

rocky canyon
radiant frigate
cinder crag
rocky canyon
#

no worries.. can u share ur code.. !code in a pastebin website.. or something other than a screenshot..

eternal falconBOT
polar acorn
rocky canyon
#

and briefly explain ur issue once more

zenith crown
radiant frigate
#

an empty? what is that?

rocky canyon
steep rose
rocky canyon
#

w/o a good ide formatting for me.. my python would be a mess

zenith crown
rocky canyon
#

thank you 👍 now whats not working?

cinder crag
cosmic dagger
rocky canyon
zenith crown
cosmic dagger
#

oh, i see, i see . . .

ashen sonnet
radiant frigate
rocky canyon
#

if u never seen code in ur life.. and want to learn code.. yea python is a go-to

#

but in context of unity.. i dont see its relevancy

steep rose
#

the only reason why i dont like python is because its way to expensive than it has to be

#

but its very easy to learn

rocky canyon
#

well, now i know who the python fan bois are 😈 lol j/k j/k

cinder crag
# rocky canyon thank you 👍 now whats not working?

so i have a chargeable bow and based on how long you charged it increases the dmg and the 35 is the max , but for some reason when i deal dmg to an enemy with the bow and then go and buy the pistol , for some reason the pistol dmg is the same as the the last bow dmg it dealt so if the player charged the bow and dealt like 3 dmg to an enemy then the next time i damage enemies with the pistol it deals 3 dmg and not 15 as its sent in the inspector so im not sure on how to fix it

radiant frigate
polar acorn
# radiant frigate i want them to be offset for an exact amount of degrees

So, you have direction, and you want two more angles offset by the same amount in either direction?

Take advantage of the fact that a quaternion multiplied by a vector applies that rotation to the vector:

direction;
Quaternion.Euler(0, 30, 0) * direction;
Quaternion.Euler(0, -30, 0) * direction;
steep rose
rocky canyon
sand heath
rocky canyon
polar acorn
radiant frigate
cinder crag
radiant frigate
#

because i have exactly that but in the "fake z axis"

rocky canyon
#

Euler (x, y z)

#

it depends on what property ur wanting to manipulate

zenith crown
#

How can i change one value to another smoothly and consistently, the 3 courses i looked into explained it confusingly

polar acorn
cinder crag
ashen sonnet
steep rose
#

brb

radiant frigate
zenith crown
sand heath
#

Y is not 'weird' it's a standard

polar acorn
radiant frigate
#

i need to write it in the z ?

cinder crag
radiant frigate
#

bulletHolder.transform.rotation = Quaternion.Euler(0,0,direction.z-30+ (30*i));

rocky canyon
radiant frigate
#

inst that what im doing?

#

maybe im confused right now

polar acorn
sand heath
polar acorn
radiant frigate
#

yes

sand heath
#

The weird one is unreal lol

zenith crown
radiant frigate
#

wait

#

im not

lethal elbow
#

I have a bit of a problem with a function I made which is supposed to make the character look towards the mouse cursor in 3D space

   private void GetMousePosition()
    {

        Ray ray = mainCamera.ScreenPointToRay((Input.mousePosition));

        if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
        {

            Vector3 direcion = Camera.main.ScreenToWorldPoint(Input.mousePosition - transform.position);
            transform.forward = direcion;
            direcion.y = 0;
            transform.position = raycastHit.point;

        }

    }
```
My problem is the character attaches itself to the mouse cursor along the layermask and I'm not sure what's wrong
polar acorn
rocky canyon
eternal falconBOT
polar acorn
rocky canyon
#

ur link is dead

cinder crag
rocky canyon
#

ooof lol

sand heath
rocky canyon
#

^ debug the value when u set it.. when u change it.. before you use it

cinder crag
rocky canyon
#

find when it doesn't work the way it should

#

when you know where its going bad.. its easy to fix

obsidian shoal
#

who else likes this font

rocky canyon
#

so the previous value from the bow is used

cinder crag
cosmic dagger
sand heath
rocky canyon
rocky canyon
#
    private void SetPOCODataToSOData()
    {
        weaponStats.name = weaponSO.name;
        weaponStats.fireRate = weaponSO.fireRate;

        if (weaponSO.name != "Bow")
        {
            weaponStats.Damage = weaponSO.DMG;
            weaponStats.BeforeDamage = weaponSO.BeforeDMG;
            BowCharge = 0f; //reset bow damage
        }
    }```
steep rose
#

back

rocky canyon
#

if current weapon is not bw.. the method sets the weaponStats.Damage and weaponStats.BeforeDamage to values in the SO

#

then it sets bowcharge to 0 to ensure that any residual charge from the bow is cleared out

zenith crown
sand heath
lethal elbow
steep rose
#

nvm

rocky canyon
sand heath
eternal falconBOT
zenith crown
rocky canyon
lethal elbow
# sand heath Send the !code again formatted
   private void GetMousePosition()
    {

        Ray ray = mainCamera.ScreenPointToRay((Input.mousePosition));

        if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
        {

            Vector3 direcion = Camera.main.ScreenToWorldPoint(Input.mousePosition - transform.position);
            transform.forward = direcion;
            direcion.y = 0;
            transform.position = raycastHit.point;

        }

    }

I thought it was to begin with

sand heath
rocky canyon
zenith crown
#

and didnt understand

#

haha

zenith crown
rocky canyon
#

it isn't being done atm

rocky canyon
sand heath
obsidian shoal
#

why is this not making xpos into a var that i can transform to

rocky canyon
zenith crown
rocky canyon
#

transform.position isnt a float

sand heath
rocky canyon
#

transform.position = new Vector3(xpos, transform.position.y, transform.position.z);

cosmic dagger
steep rose
polar acorn
rocky canyon
#

^ yup, this also..

#

the first image has a float xpos but not in the second one

lethal elbow
rocky canyon
#
    private void GetMousePosition()
    {
        Ray ray = mainCamera.ScreenPointToRay((Input.mousePosition));

        if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
        {
            Vector3 direcion = Camera.main.ScreenToWorldPoint(Input.mousePosition - transform.position);
            transform.forward = direcion;
            direcion.y = 0;
            transform.position = raycastHit.point;
        }
    }``` real formatting
lethal elbow
cinder crag
rocky canyon
#

but regardless ur paste-bin resource is much better 👍

rocky canyon
#

atleast u didnt send a screenshot.. or even worse.. a cell pic of ur monitor 😄

rocky canyon
#

it keeps the same Y and same Z of what transform.position already is

#

you can't directly set 1 property of the transform.position like that

rocky canyon
rocky canyon
cinder crag
#

slowly losing it icl

rocky canyon
lethal elbow
#

Anyone able to help with my problemo?

lethal elbow
zenith crown
#

How do i make the movetowards faster?

rich adder
zenith crown
polar acorn
lethal elbow
#

It's getting the correct mouse cursor location, the problem is it's translating the character instead of the character direction

polar acorn
#

and one of them is the maximum amount to move in a frame

cinder crag
#

hmm i saw smth but not sure if its the problem so when im in the shop tab i can still yk move around and shoot so when i press to buy the pistol , it charges the bow so maybe thats why , what if i freeze the game and then turn canFire off

polar acorn
#

and if you want it to move more in one frame

#

that's probably the one to look at

rocky canyon
#
private void GetMousePosition()
{
    if (mainCamera == null)
    {
        mainCamera = Camera.main;
    }

    Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
    {
        Vector3 direction = (raycastHit.point - transform.position).normalized;
        direction.y = 0; // Ignore the y-component to keep the direction on the horizontal plane
        
        transform.forward = direction;

        transform.position = raycastHit.point;
    }
}``` if its a 3d game i Raycast into the scene using `camera.ScreenPointToRay`
lethal elbow
rocky canyon
#
   Vector3 mouseScreenPosition = Input.mousePosition;

        /// <summary>
        /// Use Raycast Method for Casting into 3D Environments
        /// </summary>
        if (useRaycast)
        {
            Ray ray = Camera.main.ScreenPointToRay(mouseScreenPosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                Vector3 hitPosition = hit.point;
                transform.position = new Vector3(hitPosition.x, hitPosition.y, hitPosition.z + raycastOffset);
                
                if (useNormal)
                {
                    transform.up = hit.normal;
                }
            }
        }``` heres the method pulled from my own Raycast (cursor 3d script)
rocky canyon
obsidian shoal
polar acorn
lethal elbow
rocky canyon
obsidian shoal
rocky canyon
#

debug the raycast hit..

#

see if it actually raycasts into the scene..

lethal elbow
#

Ah I know what you mean, The mouse location part is fine and was originally. But when I attach it to a character then the character is attached to the cursor also

rocky canyon
#
    Debug.Log($"Raycast hit {hit.collider.name}");```
lethal elbow
#

My aim is to get the character to look towards the mouse cursor on a level y-axis

rocky canyon
#

regardless of what method u use.. the same idea can be applied.. (that.x, yourown.y, that.z)

lethal elbow
#

What's the part that connects the character to the mouse?

#

from my script

cinder crag
#

okay i fixed the dmg n stuff but now im trying to check if in the shop area then if you hold E down then you will open the shop etc but im not sure how to do it , i tried it onColliderEnter2D and OnTriggerEnter2D but nth tbh

lethal elbow
#

Nevermind, I think I've done it 🙂

true pasture
lethal elbow
true pasture
#

There's prob a better solution though I'm no expert

raw token
#

Or OnTriggerStay2D()

cinder crag
rocky canyon
lethal elbow
#

I have a new problem now and that's because the smooth camera follow is conflicting with it now haha

rocky canyon
#

sounds like u got an idea what to do/ where to look

#

best kind of problem

lethal elbow
#

I know exactly where to look, I just need to figure out why it's conflicting now 🙂

raw token
# cinder crag tried it , doesnt work

Sprinkle some Debug.Log()s around - find out what isn't working.

Two potential problems:

  • I can't remember if physics gets paused when timeScale is 0f - if it does, it would prevent you from closing the shop thingy
  • Checking for single-frame input events in a physics-relevant message like OnTrigger* may fail on occasion as their values are updated per frame, but the message will execute per fixed-step.
rocky canyon
#
    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player") && Input.GetKeyDown(KeyCode.E))
        {
            Interact();
        }
    }

    private void Interact()
    {
        Debug.Log("Interacted with E");
    }``` OnStay Method
```cs
 private bool canInteract = false;

    private void Update()
    {
        if (canInteract && Input.GetKeyDown(KeyCode.E))
        {
            Interact();
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            canInteract = true;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            canInteract = false;
        }
    }

    private void Interact()
    {
        Debug.Log("Interacted with E");
    }
``` Extra Boolean Method
#

i do something similar w/ Button's b/c theres no Stay() for buttons

#

button clicker bb!

#

isHovering

#

if theres a better method.. i'll wander up on it sometime

raw token
# cinder crag tried it , doesnt work

One other issue here is checking for key down then key up. If you tap a key, both of these events will occur in very short order - so all other things aside, this would only keep the shop open while you're holding down E

rocky canyon
#

toggles FTW

#

press E -> menuOpen = !menuOpen;

zenith crown
#

How can i change the position of my camera? When i write Camera.position.y it says its not a variable and i cant change it

zenith crown
#

thank youu

rocky canyon
eager elm
rocky canyon
#

u can't directly change the transform.position's individual properties..
you need to copy out the variable change it and reapply it

rich adder
rocky canyon
#

Vector3 newPos;

#
newPos = camera.transform.position;
newPos.x = newXValue;
camera.transform.position = newPos;``` something something
rich adder
#

yes best they read the explanation though, if we feed them they wont know why they had to do it in the first place

rocky canyon
#

i still dont know why i have to do it 😄

#

goes to read

#

Materials really messed me up..

rich adder
cinder crag
rocky canyon
#
            Material newMaterial = new Material(renderer.material);
            newMaterial.mainTexture = newTexture;
            renderer.material = newMaterial;```
rocky canyon
rich adder
#

Position is simply returning a copy Transform.position

rocky canyon
rich adder
#

you can't modify a copy it makes the whole thing useless