#🖱️┃input-system
1 messages · Page 14 of 1
yep, strangly enough all the other events are working except the switchtab left and right
I am programming a 3D game where a character gets moved by mouseclick (point and click like). The character will interact with different gameobjects.
In the beginning I used NavMesh for the player character but saw that this system just gets used for NPCs? Is it wrong/more difficult in the future to use navmesh for the player character?
there is nothing stopping you from using NavMesh for the player character and nothing wrong with doing so
It's also not really related to the input system
oh hups. and thanks
@austere grotto I was able to fix my problem by reverting the package changes in source control
i have made a 2d vector input and hooked it up to my movement system, and it works perfectly fine with the gamepade, but doesnt work at all with WASD. any clue why?
i figured it out!
had to add them as supported devices
any documentation of return type of every action control type? or even a description of each action control type?
i have been using the runtime way, thanks for the docs page😸
I've been working on AI for my thesis the past couple of days, and i've reached the point where i need to "Fake" a Device.
as a nutshell, my GameObjects that are either playable characters or enemies can technically be played by the player, this is done by having a component which is basically an InputBank for the gameObject. and having a "Master" game object which feeds the inputs to the input bank.
for the playable master its easy, i just made a custom component that uses the PlayerInput component and tie buttons to actions.
However, for AI, the AI itself wouldnt have a device, yet i would still need to "fake" certain inputs like buttons, how could i achieve something like this?
https://hastebin.com/share/vimafemoru.csharp this hastebin should contain what i mean by my "master" and "input bank"
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i think i might be able to "fake" the inputs by adding devices that arent wired to hardware directly
Highly recommend abstracting input handling away from the code with something like a per-fixedupdate "input struct".
Basiclly the technique used by networking frameworks for input are the sme concept. Example from photon fusion:
Input definition, polling and consumption lie at the core of Fusion. Back To Top
The input struct can store as simple or as complex data as needed.
In essence your AI then just needs to populate an input struct as its output each frame
hm, i see
so basically make it so the "Button" struct isnt precisely tied to an input action
thats what i understood anyways 😓
actually
ok yeah i get what you mean
Basically you want to separate the input from the gameplay entirely
yeah
each frame you want a chunk of data. Just a contrived example:
public struct InputState {
Vector2 stickDirection:
bool jumpPressed;
bool crouchPressed;
}```
your input handling code (input system related) should just populate that struct
your gameplay code should just consume this struct each frame
noted
the AI can then easily replace the input system input handling code by simply generating this struct each frame
it doesn't have to deal with the real input system at all
due to the nature of inputs, i should ideally always handle it on Update instead of something like fixed update, right?
otherwise i think i run the risk of the player ending up with ghosted inputs
(i think thats the term...?)
Yes that is true, but you can populate the input struct in Update and consume it in FixedUpdate
aight just finished moving my playable character's input to this system
so, just gotta start working on the ai side of things
thanks
what is Gravity in input Manager?
I'm trying to make 3 axis in plane
oh nvm just found docs
Can a player input component only exist 1 spot? I am trying to put 1 for movement and 1 for looking but when I enable both only one works, when I enable one, it always works
Why would you make a whoile nother PlayerInput component just for a different action?
It's intended to be one PlayerInput per user
ok
The new input system is not working on build. In Windows there is no input detection at all. In WebGL I get this error showing up. I'm using new input system 1.3.0 and Unity 2021.2.17f. If I use the old system in code then the build works fine both in webgl and windows.
Kinda sounds like the type of error you might get if you made changes to the input actions asset but are still using an old version of the generated C# it produces
how can i check if the Tilde key was pressed on the current Keyboard device
is there a fix for when the input system just stops working? right now it seems i have to change the player input behavior, then change it back to get it to work again.
i spent a good chunk of today working on the input system
So I'm having a bit of an odd issue here. I've made a scriptable object to handle my player input and have a function that swaps between the UI and Player maps. So while my UI pops up the player is still able to move. I feel like it might be an issue with how I assigned each event in the editor but I'm not entirely sure
You'd have to show the code that handles the input. Most importantly are you certain you're using the same input action asset for both scripts?
Could someone help me by explaining the basics of CallbackContext? I've read the unity docs but its left me more lost than trying to figure it out by myself 😂😭
The system responsible for handling inputs collects the context before invoking the input actions. Access to this context lets the developer read some additional info about the input, e.g. you can check what kind of button was pressed, when the action started, or what device registered this event. This kind of info can be used for debuging purposes (e.g. to figure out that "charging" might be also registered as device input) or to use it for gameplay/UI purposes (e.g. when someone presses a gamepad button, you could switch all the key buttons displayed in your UI from keyboard buttons to gamepad buttons).
The context itself can be completely ignored if you don't need it. It's just here to help you if you need it.
So I assume then that the CallbackContext would be inappropriate for returning the on-screen location of an event? Correct me if im wrong please, im desperately trying to learn this so I can use it in my game but its quite complex
CallbackContext doesn't return such info. I think Mouse.current.position.ReadValue() should work for the mouse position on the screen.
Hello. I’m having issues with the on-screen controls with the new input system. I’ve had it working perfectly before so I’m not sure what broke. I’ve also followed tutorials that produced the same results. Basically, I subscribe to the action, and then call one of the buttons like “gamepad left stick” with the on-screen stick controls. It only seems to work if I enable the “auto-switch” button in the player input class. However, the controls are extremely jerky, get stuck, and don’t move properly. If I turn off “auto-switch”, things move smoothly but don’t call the actions anymore. I've linked my settings. Any help would be greatly appreciated.
{
[CreateAssetMenu(fileName = "Input Reader")]
public class InputReader : ScriptableObject, PlayerController.IPlayerDefaultActions, PlayerController.IUIActions
{
private PlayerController _playerController;
private void OnEnable()
{
if (_playerController == null)
{
_playerController = new PlayerController();
_playerController.PlayerDefault.SetCallbacks(this);
_playerController.UI.SetCallbacks(this);
SetActionMap("PlayerDefault");
}
}
private void SetActionMap(string newInputActionMap)
{
foreach (InputActionMap inputActionMap in _playerController.asset.actionMaps)
{
if (inputActionMap.name == newInputActionMap)
{
Debug.Log(inputActionMap.name + "is Active");
inputActionMap.Enable();
}
else
{
Debug.Log(inputActionMap.name + "is Inactive");
inputActionMap.Disable();
}
}
}
#region Player Event Actions
//Directional Movement
public event Action<Vector2> MoveEvent;
//Player Action Buttons
public event Action JumpEvent;
public event Action PrimaryFireEvent;
public event Action AlternateFireEvent;
//Mouse Look
public event Action<float> LookXEvent;
public event Action<float> LookYEvent;
//UI
public event Action PauseEvent;
public event Action ResumeEvent;
#endregion```
public void OnLookY(InputAction.CallbackContext context) => LookYEvent?.Invoke(context.ReadValue<float>());
public void OnLookX(InputAction.CallbackContext context) => LookXEvent?.Invoke(context.ReadValue<float>());
public void OnJump(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
JumpEvent?.Invoke();
}
}
public void OnPrimaryFire(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
PrimaryFireEvent?.Invoke();
}
}
public void OnAlternateFire(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
AlternateFireEvent?.Invoke();
}
}
public void OnSwapWeapon(InputAction.CallbackContext context)
{
}
#endregion
#region UI Mapping
public void OnResume(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
ResumeEvent?.Invoke();
SetActionMap("PlayerDefault");
}
}
public void OnPause(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
PauseEvent?.Invoke();
SetActionMap("UI");
}
}
#endregion
}
}```
Is there an easy way to make a Scrollbar move a ScrollRect smoothly?
Or alternatively, make a Slider scale it's own handle's size like a Scrollbar does?
If I use a Slider I can easily write a little script that uses Smoothdamp to make the UI slide in a really pleasing way.
It's also easy to set step size for them.
...But it won't resize like a Scrollbar does.
If I use a Scrollbar it resizes well, but looks kind of garbage when scrolled with a keyboard.
It just sets ScrollRect position with 0 smoothing and after several hours I found no way to change that behavior.
The best solution I've managed so far is to have an invisible Slider behind the scrollbar that "hijacks" controls, but... I feel like I'm going something questionable. 
I also made sure I have the same one for both scripts
Is this all one class?
or is it two classes
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
bet thx👍
I can not for the life of me figure out what is going on here.
So I got a new PC, and haven't worked on this game for a little bit. Now I want to get back to it, and the input system (new) is just not reacting at all. The "Active Input Handling" is set to "Both" and I still see all the settings/setup of the input system, etc.
Just to confirm some of the other things I've checked:
- Code is still set up and does enable the right action map
- The Actions are still set up correctly (just testing WASD for now)
- The code is calling it correctly
- Attempted to debug the 2D Vector of WASD, and it just return 0.00, 0.00. As if nothing is affecting it, no matter what I am pressing.
Anyone got any idea?
ok so... at first glance... It seems like it should work. The main issue I see is that the OnResume and OnPause things are part of the UI action map meaning... presumably you wouldn't be able to pause while in game mode?
I put both of them in UI Mapping for readability's sake. As for OnPause and OnResume themselves the resume and pause are on different action maps
Are you getting a log that says "PlayerDefault is Inactive" for Debug.Log(inputActionMap.name + "is Inactive"); ?
Whenever I start the game I get both that the "PlayerDefault" is active and that UI is Inactive
which changes when I press escape to pause
wait now I can't move the player what
You should disable the Collapse setting in the console
srry for the late response, got caught in the middle of stuff. Turns out it's outputting the same messages twice
Hey guys, I want something to be applied while a button is being pushed down, but reverted on release. Think like Tetris, how holding 'down' speeds the block up, but letting go returns it to its regular falling speed. Is this possible?
Not a question, just a huge thank you to whoever works on the new Input Action system and added a full explanation to the Enable(). This is extremely convenient and helpful ❤️ Whoever made that THANK YOU
(I know that this will probably never reach that developer but one can dream and hope that it somehow may reach them.)
so i am trying to make some controls for mobiles using the on-screen button,it works as usual,but when the touch moves from the button,it stops sending input,even when the touch is still on the button,any idea how to fix this?
why does this not work? context.canceled doesn't seem to do anything/trigger?
Have you added Press Interaction with Press And Release trigger?
I have now and it's still not triggering the debug log
So far i have tried adding custom interactions,changing the type from pass through to button and even adding a button component,but it still doesn't work,any idea on how to fix it?
default press point doesn't change it
Any help anyone?
You shouldn't have any interaction
Also your action is set as a 2d vector so canceled will happen when you fully release the joystick
there's no joystick, it's only on S
so whats the scripting to make it happen?
not a scripting issue
set up the action and bindings properly
What button do you want to perform this action?
ok so just make it a button action and make a binding for the S key
remove any and all interactions
like this? nothing happens on release then
how did you hook up the action to the code?
that's a huge missing puzzle piece here
and key to your problem
if you are only subscribing to the performed action, for example, that explains it quite easily.
no
i saw this already
you need to show how this function is hooked up to the action
there's a piece in the middle
idk what you mean
show your full script
or are you using the PlayerInput component?
there is a glue piece
otherwise how does it know that function is linked to that input action?
there's a huge piece missing from your description here
yep exactly as I thought
you are only subscribing to the performed event
if you want canceled events, you have to subscribe to canceled
e.g. moveDown.canceled += SomeFunction;
ah i see
you can either subscribe the same function and do the if / else you are doing now, or you can use two different functions
that's one option
huge tyvm
Anyone can help?
_PlayerInput = The player input component on the same game object. Not getting any readouts from this
I am pretty sure I was earlier
did you assign the player input?
I mean I have a bunch of stuff working for input already using the input-system
Did you set the PlayerINput component to "C# events" mode?
also what is OnStart?
That is not a thing in Unity so it won't run unless you run it yourself
Maybe you meant to write private void Start() ?
also when testing on pc using the device simulator,it seems to stop whenever another input is active
I'm having a similar problem as @woeful inlet with the on-screen buttons not sending events. I found that if I turn on "auto-switch" in player input, it makes the events fire, but the buttons/joystick don't work properly and get stuck. If I turn off "auto-switch" the buttons/joystick move smoothly but don't trigger events.
are you talking about buttons or joysticks?
I'm having issues with both. The joystick gets stuck and doesn't send accurate events. The button is also inconsistent.
Is there a way to subscribe the whole action ? I mean not only one callback ?
Should I subscribe every different Callback ?
I mean, hmm, strange.
Don't hesitate to @ me or even dm me ! <3
When creating an instance of ScriptableObject from code, how do you point to a specific Object that you made off of that ScriptableObjectClass?
What do you mean?
I make a scriptable object class
I then make a new asset based off of it and give it data through the inspector
MyClass newInstance = ScriptableObject.CreateInstance<MyClass>():
Is this what you mean?
Right but that returns only the base
Wdym by the base
not an asset made from it
if I make something like this
i won't get it's data from creating an instance for the SO
Drag and drop it in the inspector
Is that the only way to get it's data?
Well like if I want to create data off of the SO for each type of weapon for example, and then have a parent class for weapon automatically select the the correct data on Start based off of the parent game object name or something
rather than drag the relevant asset to the prefab every time
There is no way to do something like
WeaponsSO swordData = ScriptableObject.CreateInstance<WeaponsSO>(IronSword):
Print(swordData.Damage);
You only have to drag it once
Much better than using inheritance
Is it better to trigger player movement using the event-based approach with the input system, or should I use the auto-generated input actions and read the value each frame in update? I would think the event-based approach would be more performant, but a lot of the tutorials seem to readvalue in update so I'm a bit confused
Update makes a lot more sense for something like a continuous movement handling, in my opinion
not sure how the event would be more performant in that case considering it would just be running more or less every frame anyway
When you're not moving or jumping, you're not checking if .isPressed() every frame. I know it's a small check, but I was just wondering why you wouldn't want to do it via events instead?
It might matter if this was for many objects, but an update loop on the single player instance in the game is nothing
also the event system is polling the input every frame anyway
you're simply not going to see a noticeable performance difference either way
So they're essentially equivalent?
That's good to know that the event system polls input every frame. If that's the case, then I'd imagine I can just leave my code the way it is. One of the concerns I had was if the events could come in late and cause input lag
hey so ive got this issue where when i switch from one weapon to another my way of "looking" changes. i think this has something to do with the code of both of the weapons. ignore the errors, would really appreciate the help since ive been trying for over a day to get this issue fixed
these screenshots really aren't showing us anything that could be helpful in solving your issue
i meant to show that the pov changes when i switch from one weapon to another as it shows in the screenshots
ok well.. seeing the code owuld obviously be helpful
it wont let me send the entire code, instead it gives me a .txt document, is that okay?
im hoping it isnt against server rules
no
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i cant really send the entire code because of not having nitro
bare with me
ill send the code by chunks at a time
read the thing
you didn't read the thing
alr dude lol
im reading the thing
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
read the thing
im guessing this is the wrong channel
kindayeah this isn't an input system issue
but
private Vector2 _currentRotation;```
each gun has its own rotation variable
so when you switch, it's gooing to switch rotation
it's unclear why this FPS controller stuff is on the gun script?
i tried to make everything work using as little scripts as possible but that didnt realllly work out
"as few scripts as possible" is not a good plan for laying out code
yeah but the rotation stuff is tied to a bunch of other stuff so if i remove it i wouldnt be able to look around
learned that the hard way
do you suggest doing anything else?..
I suggest refactoring your scripts so that there's an FPS controller on the player itself and the gun scripts only handle gun/shooting stuff
man i want to shoot myself
refactoring and redoing your scripts is a constant process
you can't expect to just write code once and forget about it, that's not how game develeopment or any programming project works
there has to be an easier way
Welcome to game development
wait dude i got an idea
listen can you lend me a script that you use that makes you look around?
let me try atleast man
Does Input.GetAxis("Mouse ScrollWheel") works fine?
It seems trash
this thing can't catch My Mouse wheel Scrolling
Is anyone else having issues with their on-screen controls? My on-screen joystick/button aren't working properly, they keep getting stuck. If your controls are working properly, could you send me a screenshot of your event system and player input settings? I would greatly appreciate it. Thanks!
im using cinemachine and i havent added an ui for the touch screen but touch is still working , i wanna know how can i make the screen movement touch not work on some parts of the screen
as im using package for the movement controls the camera touch is still working on top of the movement joystick button
it only works with the old input system
Any help anyone?
im having two inputs
the delta for camera control and a joystick for movement
but these buttons are overlapping when i touch on screen
can someone help me fix this ?
how do I add scrolling in/out into my game using Input manager
I'm making a game and I'm trying to change to the new input system. I have a prefab that is used as different signs and is currently having "DialogInteraction" script. The thing is this DialogInteraction script was made to be customable(the text). It has 2 box collider; 1 for making it physical and 1 for the TriggerEvent to activate when the player is in this boxcollider. The Player Input is a component on the player and not the prefab. I really don't know how to solve this...
i just started a new project and im trying to setup the new input system. sendmessages isnt working at all for some reason
am i doing something wrong here? when pressing any of the movement keys the function never gets called
OnMove needs to have an InputValue parameter
changed it to this but its still not working
should work 🤔
What buttons/keys are you pressing?
also do you have any errors in console?
no errors, ive tried replacing the method with onjump (space) and onfire (mouse left) but nothing works
for move im doing keyboard A and D
can you use
Input.GetAxis("Axis name") with the new input system
You can set your project to use both input systems. I think it's Edit > Project Settings > Player? > and like 2/3 of the way down.
Not sure exactly where
Yes, in player. And it's called "Active Input Handling"
I don't want to use both input systems I was just wondering if you get inputs using the same method
No, that is the old method for the old system
I'm not sure what you're asking. It's a package they just call Input System
That is a huge topic. There are a ton of guides you can find online. There's a few different methods too. Like event and message based. Or more reminiscent of the old system with: Keyboard.current.AKey.isPressed (i think that's right).
It's way too much for me to explain here though
ok I'll just find a brackeys tutorial lol
If anyone has on-screen controls working properly, could you send me a screenshot of your event system and player input settings?
My problem still isn't solved
Instead of doing it Update, use the callback method to just check if the inrange bool is true. If it is, interact
So just get rid of the part startung with the old input and put it in the callback method
It can work in another script from another object?
(Some context) The Player input is a component of Player, and this script is a component of Sign.
You could have the sign script give itself as a reference to the player (and when out of range, that reference is null). You just nullcheck when you get the input callback, on the reference on the player. If not null, call the method through the reference
That would probably change your scripts the least
Otherwise I would invert that, and have ALL that logic on the player, and simply see if the DIALOGUE box is in range
Yeah I thought of that too but wasn,t sure on how to see which specific Signs is since I will have multiple displaying different text
Would there be a way to get text from an object close to the Player?
Well, you'd just check if ANY dialogue box is in range, and all of them would have the same "display text" method to be called by the player
The dialogue box would handle that itself
But that would mean the method would display a static text?
? Each dialogue box would have its own text, which could be dynamic
I'm a bit confused by how it would differentiate a dialog interactive object from an other... I'm sorry if you are right
By range, right? Just like before, when you enter trigger range
I will try things with what you told me I'm not sure if we understand each other. But here some precision and you tell me if it's what you understood or not: I have a Player and when the player is around a Sign, the Player can interact with the Sign. The sign would need to have a specific and customable text to it since there would be many with different things to say. When the player hits the interaction key, the dialog box show up.
If I try your idea, that means I need a way for the text contained by the Sign to go to the method in Player which I don't know how to do or maybe I forgot how.
Or maybe I didn't understood your explanation? Feel free to say if I'm wrong
(If it can work your idea is great!)
So, your sign has ontriggerenter. If it detects the player, it gives the player a reference to itself. If the player hits the input, it checks if that reference is null. If not, it says sign.DisplayText and the sign displays its own text
In the signs ontriggerexit, it tells the player to set that reference to null.
Or the opposite, where the player gets and nulls that reference. Doesn't matter.
The player does NOT need the text
Mhh ok it's a bit more clear. So I keep this script to the Interactive Object, but I reference the player. I don't quite understand this part... But thank you because I already see progress
The sign would have
OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player")
{
collision.GetComponent<Player>().SetClosestSign(this);
}
}
Ok, and so I would need to make a function "SetClosestSign(text parameter)" to set the text?
Player would just have:
if (closestSign != null) {
closestSign.DisplayText()
}
In your callback method
No! It would give the sign script
Oh oh ok
SetClosestSign(SignScript sign)
You would just write "this" in the parameter, which would refer to the script itself
Is this method already exist?
No. You would make it. It would just set a variable to the script
And you'd have to make one to set it null in the OnExit method. Or use a default parameter of null so you can just do SetClosestSign()
Sorry for the waiting I'm trying to understand
To break it down:
Sign has text. Player has input. Sign tells nearby player it is close. Player responds to input by asking nearby sign to show its text. Sign shows its text
No worries. I gtg anyway. Good luck!
Oh ok well thank you very much still
Btw, there are plenty of ways to do this, I just thought this would just be the easiest to explain and require the least change to your code.
So someone may recommend a different way later
Yes I needed a little help to get into this it's not solved but at least I have more ideas now because of you 👍
Oh totally. No worries. You go with whatever feels best to you!
any other ideas for this btw?
so I was following a brackeys tutorial (https://youtu.be/p-3S73MaDP8) and I am getting error error CS0246: The type or namespace name 'PlayerControls' could not be found (are you missing a using directive or an assembly reference?) when using this code:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
private CharacterController control;
public Transform cameraTransform;
PlayerControls controls;
void Awake()
{
control = GetComponent<CharacterController>();
controls = new PlayerControls();
controls.Gameplay.Jump.performed += ctx => Jump();
}
void Jump()
{
}
void Update()
{
cameraTransform.position = new Vector3(transform.position.x, transform.position.y + 1.2f, transform.position.z);
}
}
I am fairly new to this and don't even know where to start troubleshooting which is why I came here
When you made your input asset, did you call it PlayerControls? And did you generate the c# script for it?
oh I didn't generate the script
thanks I forgot about that
im so confused, now whenever my playermovement script (which is totally empty btw) is attatched to the gameobject with the player input component, i get this error when pressing A or D (bound to the move action in my input settings)
MissingMethodException: Method 'PlayerMovement.OnMove' not found.
adding the method changes nothing
none of the other actions like jump (spacebar) or attack (mouse left) bring up an error or do anything at all
why doesnt sendmessages work 😭
Does it have the right parameter? It needs InputValue
turns out that both input systems were enabled, changing it to only the new one fixed the problem
whats the proper way to do movement with the Player Input component? not really sure how since things like the OnMove function is only called the instant a key is pressed
so i am trying to make some controls for mobiles using the on-screen button,it works as usual,but when the touch moves from the button,it stops sending input,even when the touch is still on the button,any idea how to fix this?
Save the input value in a variable and use it elsewhere
It depends on the type of movement though
Hello, I'm not sure I've understand this well (Bc I feel like english used is a little complex), if someone car take 2 minutes and tell me if I understood well this chapter of the video (https://youtu.be/rMlcwtoui4I?t=624)
So, actually, what I understand is that when having an input action on a binding and on an action, the bindings one will have the priority on the action one.
Using this concept, if I have a hold interaction on the binding and a tap interaction on the action what it will do is check the hold one first and then, if I cancelled the hold one, it will check if the tap one has been performed and return true if one of those two is succesfully performed.
Too, it seems like having more than one interaction on a binding or an action have the same kind of behaviour, it will first check the interaction which is the most down and then, start to check the upper one.
Btw, I'm so sorry for asking that, as I said it's just that it seems a bit complex for me but I guess if I understood this well, I can understand way more than I think !
YouTube
(It's a repost of the #💻┃unity-talk because I don't know where to post it lol)
Today we go over Interactions in Unity's New Input System. I go what makes an interaction, how it impacts the actions, the individual actions themselves, code overview, interaction priority and multiple interactions, and custom interactions.
📥 Get the Source Code 📥
https://www.patreon.com/posts/54177140
🤝 Support Me 🤝
Patreon: https://www.patr...
im using C# events for my input system, i want to make a 2 player fighting game, ive set up my script and action map. player one and 2 are both moving together when im using either of the controls that the players are paired too.
heres the code i have so far
`private PlayerControls inputs;
private float iputrefersh;
private float reshreshtimer;
protected override void Awake()
{
base.Awake();
inputs = new PlayerControls();
inputs.PlayerController.Attack.started += Attack_Started;
inputs.PlayerController.Attack.performed += Attack_performed;
inputs.PlayerController.Attack.canceled += Attack_canceled;
inputs.PlayerController.jump.started += Jump_Started;
inputs.PlayerController.jump.canceled += Jump_canceled; ;
inputs.PlayerController.skillSetup.performed += SkillSetup_performed;
inputs.PlayerController.skillactivation.performed += Skillactivation_performed;
inputs.PlayerController.Dash.performed += Dash_performed;
inputs.PlayerController.Enable();
}
public Vector2 Movement()
{
Vector2 rawMovement = inputs.PlayerController.movement.ReadValue<Vector2>();
int normInputX = (int)(rawMovement * Vector2.right).normalized.x;
int normInputY = (int)(rawMovement * Vector2.up).normalized.y;
Vector2 movement = new Vector2(normInputX, normInputY);
return movement;
}`
If you want to make a local multiplayer game the easiest way by far is to use PlayerInputManager and the PlayerInput component
the code you have here does nothing whatsoever to distinguish the players and split up the input devices by player
PlayerInputManager handles all of that for you
ah i get it thanks
can i modify my code so that it uses the "player Input " rather then the genreated C# script, cause i dont want to setup things in the inspector
thankyou kind sir i have solved my problem thankyou soo much sir
any tutorials on how to convert a script from the old input manager to the new input system
not really
but you can use Keyboard.current or Mouse.current
these can't be changed dynamically though
Hi, How do I detect both mouse down and up with the new input system? I'm using Unity Events to connect to scripts
started/canceled phases on the callback context
already figured that out, thanks
is there a way to increase the update rate of the input system? seems that is at ~60hz
it is the same s your game's framerate by default
doubt, as i turned off vsync and i am still at ~60
anyways, is there a way to increase it to 250hz oder even more ?
how are you determining the update rate
what change?
input change of single actions/bindings
like in a performed callback?
That will only happen when the value of the thing actually changes
i log the raw value
Ok that's a screenshot of your settings but not an answer to my quesiton
though it is an answer to your question
yeah give me a sec i ll fire up vs
fixed update is @333hz
I would try this:
- set update mode to dynamic update
code:
void Update() {
print($"Frame {Time.frameCount}, value: {someAction.ReadValue<float>()}");
}```
see if it changes every frame while moving a joystick around
and yeah it goes via the events of the player input to my own class
yeah that only happens when the action is performed
which only happens when it detects a change
ok so the change has a threshold ?
I don't think so - but your hardware device might, or it might not be changing that fast
i would rather use the fixed update than dynamic one as i need the fixed rate
hardware device can atm go as fast as the usb controller and windows is actually allowing it
over air i can reach paket rates of over 1khz
so HID would be limiting factor
hmm but then it should fire more often then what i actually see
orange graphs are changes of analog sticks
as you can see they are irregular
hm
or it is really the fixed rate ...
@sweet roost just found this seems quite relevant lol
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_pollingFrequency
oh nice
default is 60 😄
time for testing
i think i also have to detach the input update from the fixed updates, as fixed updates happen all at the same time more or less...
yeah I don't think the fixed update mode is that useful unless your fixed timstep is much lower than your framerate
yeah you are 100% right
but it is usefull for the other stuff i have 😄
hmm On Win32, for example, only XInput gamepads are polled.
but still i guess i have to get rid of the updates in fixedUpdate
i assume it is windows or the HID driver or so ...
state updates in the input debugger are ariving really fast at ~2ms
but i dont know if the values actually change there...
Make an action with settings:
ACtion Type: Value
Control Type: Vector2
Then make an up/left/right/down composite binding for it and assign the keyboard buttons to it
in action with modifier. the modifier and binding are interchangeable?
i want to have a directional dash. but I want the character dash back without turning if player pressing shit + A (or thumbstick left + r1)
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I am having some trouble with interactions
specifically the tap interaction
no matter what I do it always takes a bit too long to register that was pressed
you can see the delay between the "started" message and the other interaction types
multi tap and hold work as intended
but tap just takes a bit too long
It's impossible to tell the difference between a tap and a multi tap without waiting for the multitap time limit
oh
that makes sense
so the only way to make the tap faster is to make the multitap ludicrously fast
How can I get the current control scheme used without using the PlayerInput component? I'm generating C# classes on my input actions instead and reading the values directly
is an action with the press interaction with "press only" supposed to fire only when pressed and not on release,right?
A press only press interaction is basically the same as having no interaction at all
the only reason to use it is to customize the "pressPoint"
i already found a solution,but thx anyways
You didn't present an issue, just a question ¯_(ツ)_/¯
well it was a question for an issue
I have an issue where my xinput controller (8bitdo sn30 pro) maps both the left and right shoulder buttons to the left stick press when I export my game to android, but it does not happen in the editor, so what could be the cause of it?
Is anyone getting this problem?
I double the number of PlayerInputs every time I reload the scene.
@wintry marsh try starting at 0 instead of -1, -1 is the last item in the list, thus leaving the rest of the list untouched
Create a new instance of your input actions c# class with the constructor in script and call its Enable method.
Not what I needed but thanks anyway
public class GetSteps : MonoBehaviour
{
public TextMeshProUGUI text;
void Start()
{
#if PLATFORM_ANDROID
if (!Permission.HasUserAuthorizedPermission("android.permission.ACTIVITY_RECOGNITION"))
{
Permission.RequestUserPermission("android.permission.ACTIVITY_RECOGNITION");
}
InputSystem.AddDevice<StepCounter>();
InputSystem.EnableDevice(StepCounter.current);
#endif
}
void FixedUpdate()
{
if (StepCounter.current.enabled)
{
text.text = $"Steps: {StepCounter.current.stepCounter.ReadValue()}";
}
}
}
when i launch the app it asks for permission to track physical activity which i allow, but the number of steps always stays 0 on my android phone. is there something im doing wrong here?
if (input)
move(pleyer.input)
def move(waht)
foreach(waht in pleyer.burger)
pleyer.changepos(waht - Screen.height();)
I'm very embarrased at the fact that this Input System is really getting my emotions out.
Anywho, i can't jump, for some random reason. the jump bool in the following script simply does not want to co operate and just show as true:
here's my code:
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class Movement : MonoBehaviour
{
CharacterController controller;
[Header("Movement")]
[SerializeField] float speed = 11f;
[SerializeField] float jumpHeight = 3.5f;
[SerializeField] float gravity = -30f; // -9.81
[Header("Looking")]
[SerializeField] float sensitivityX = 8f;
[SerializeField] float sensitivityY = 0.5f;
[SerializeField] Transform playerCamera;
[SerializeField] float xClamp = 85f;
float xRotation = 0f;
[Header("Basic Flags")]
[SerializeField] bool Move;
[SerializeField] bool Jump;
[SerializeField] bool Look;
[Header("Internal Variables")]
bool jump;
Vector2 horizontalInput;
Vector2 verticalInput;
Vector3 verticalVelocity = Vector3.zero;
[SerializeField] LayerMask WhatIsGround;
[SerializeField] bool isGrounded, jumping;
NewInput controls;
NewInput.FPSControllerActions _FPSController;
private void Awake()
{
controls = new NewInput();
_FPSController = controls.FPSController;
_FPSController.Jump.started += _ => OnJumpPressed();
controller = GetComponent<CharacterController>();
}
private void Update()
{
isGrounded = controller.isGrounded;
jumping = jump;
if (Move)
DoMove();
if (Jump)
DoJump();
if (Look)
DoLook();
}
void DoJump()
{
if (jump)
{
if (controller.isGrounded)
{
verticalVelocity.y = Mathf.Sqrt(-2f * jumpHeight * gravity);
}
jump = false;
}
verticalVelocity.y += gravity * Time.deltaTime;
controller.Move(verticalVelocity * Time.deltaTime);
}
public void OnJumpPressed()
{
jump = true;
}
}```
You need to do controls.Enable();
i did, sorry, its not shown in this excerpt as discord 2,000 character limit.
If you want help share your full unedited script.
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
how can I fix incorrect mapping of gamepad inputs on android, my left stick press and both shoulder buttons all trigger the left stick press on my phone, but not in the unity editor.
it looks like you're checking Jump to see if you should start a jump, but your jump button listener is setting jump
Nope, Jump is a flag
so i dont have to make different scripts for different things, if i want the player to be ABLE to jump, i set the Jump flag to true in Inspector
oh i see, it's very confusing to have jump, Jump, and jumping in the same script lol
😭ye i just realized
maybe i shouldnt do that lmao
but regardless, its all good, i just rrwrote it in a different way, and i broke a different part of the script, but hey, at least jumping works!
How do I get rid of these? They got added automatically at some point and if I delete them I get errors like this in console: ArgumentException: Input Button Enable Debug Button 1 is not setup.
URP adds these I believe
I don't think you can remove them nor is there much of a reason to
I see. They're just ugly and make it seem like I set something up incorrectly
They are there to enable this functionality I believe:
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@16.0/manual/features/rendering-debugger.html#how-to-access
gotcha, thank you for the context
Hey this one right here doesnt work, ONMove is a built in function right? It doesnt even Debug tho
maybe you forgot to enable the action map
Where can I?
it's not built in, no
it would depend on how you set up your input actions asset
if you have an action named "Move" and are using "broadcast messages" mode on your PlayerInput component, that's when this function would be called
How can I Lerp scaling from 1 to 0 over 3 seconds?
I got it..
you add a binding to it
You probably want Action Type - Button
if you just want to detect presses of a key
I am trying to use new input system...
public void Move(InputAction.CallbackContext context)
{
if (!IsEnabled)
{
return;
}
if (context.started)
{
_direction = context.ReadValue<Vector2>();
Debug.Log(_direction);
}
if (context.canceled)
{
_direction = Vector3.zero;
}
}
This is my WASD movement method, but it moves only horizontally, or vertically, but never diagonally (when i hold e.g. W+A) anybody have solution for this, I am really frustrated by this issue 😦
you are ignoring the performed phase
which is like... 99% of the callbacks you will get
there's not really any good reason for you to be caring about the phases at all here honestly
you can replace
if (context.started)
{
_direction = context.ReadValue<Vector2>();
Debug.Log(_direction);
}
if (context.canceled)
{
_direction = Vector3.zero;
}```
all of this^ with:
```cs
_direction = context.ReadValue<Vector2>();```
MAN! You just solve my almost 4 hours issue within two minutes 😄 Thanks!
Do I understand correctly that "Performed" is like "In progress" state?
performed is when the action is performed
it's when "the thing" happens
it's very vague because the input system has such a wide variety of use cases
for example, you have an action with a "Hold" interaction. After you hold the button for the designated time, then performed will happen
but for a typical joystick bound action, performed happens every time the stick moves to a new non-zero actuation position
Oh I see. Thank you a lot for clarification 🙂
Is there an better way to do that?
https://forum.unity.com/threads/ui-button-click-perform-input-action.1468040/
I'm sorry I read your question and cannot make heads or tails of what you are trying to do
My bad. Let me try to rephrase.
I want to have a button on the ui and button on the keyboard that acts in the same way.
When I tap it. It will toggle X on. Tap it again will toggle X off.
When I start holding it will toggle X on and when I release that hold it will toggle X off. ( so the user doesn't need to double tap to toggle off).
I have done this with the keyboard press and works nice.
Yet how do I add a UI button to this action? So when I press on screen image button it will act the same way as the keyboard button.
I can't seem to figure out if there is a way to do this,
i.e.
mouseDown on image
inputaction?.invoke( performed)
mouseUp on image
inputaction?.Invoke (cancelled)
OOOoooooooo. I don't know how did i miss that lol. Ama try this real quick brb in 10 minutes. Thank you ❤️
@austere grotto SendValueToControl(1.0f); Inside the OnScreenControl. doesn't seem to be working.
Any ideas why?
I imagine that it's just supposed to just trigger the button as it would be keyboard button.
I have created also custom class. Where debug gets triggered yet it doesn't trigger the button like a keyboard button does. ```public class TestUIButtonControlMono: OnScreenControl, IPointerDownHandler, IPointerUpHandler
{
public void OnPointerUp(PointerEventData data)
{
SendValueToControl(0.0f);
}
public void OnPointerDown(PointerEventData data)
{
Debug.Log("TestUIButtonControlMono d");
SendValueToControl(1.0f);
}
[InputControl(layout = "Button")]
[SerializeField]
private string m_ControlPath;
protected override string controlPathInternal
{
get => m_ControlPath;
set => m_ControlPath = value;
}
}```
uhh
Is there a reason you're doing all this?
instead of just using this component:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.3/manual/OnScreen.html#on-screen-buttons
Because the premade component doesnt work also
wdym
so i was making sure that the ui buttons works at all
what's wrong with it
It has the same code as my class right ? Where my class debug.log gets triggered. The send value doesnt appear to do anything
It has the same code as my class right
Does it?
How can you assume that
i opened it ```#if PACKAGE_DOCS_GENERATION || UNITY_INPUT_SYSTEM_ENABLE_UI
using System;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.Layouts;
////TODO: custom icon for OnScreenButton component
namespace UnityEngine.InputSystem.OnScreen
{
/// <summary>
/// A button that is visually represented on-screen and triggered by touch or other pointer
/// input.
/// </summary>
[AddComponentMenu("Input/On-Screen Button")]
[HelpURL(InputSystem.kDocUrl + "/manual/OnScreen.html#on-screen-buttons")]
public class OnScreenButton : OnScreenControl, IPointerDownHandler, IPointerUpHandler
{
public void OnPointerUp(PointerEventData eventData)
{
SendValueToControl(0.0f);
}
public void OnPointerDown(PointerEventData eventData)
{
SendValueToControl(1.0f);
}
////TODO: pressure support
/*
/// <summary>
/// If true, the button's value is driven from the pressure value of touch or pen input.
/// </summary>
/// <remarks>
/// This essentially allows having trigger-like buttons as on-screen controls.
/// </remarks>
[SerializeField] private bool m_UsePressure;
*/
[InputControl(layout = "Button")]
[SerializeField]
private string m_ControlPath;
protected override string controlPathInternal
{
get => m_ControlPath;
set => m_ControlPath = value;
}
}
}
#endif
what control path did you use?
and if the code is the same what was the point of overriding it?
I tried several Keys L S LCtrl
^
this to make sure
but did you actually bind any of those things to the action in question?
its not my fault at setting just a button
normal keyboard button works
when I press L on my keyboard i can see it changing and working
when i press the on screen one it doesnt work
was your log printing?
there is no message from the inputsystem there is a message that I made in custom class only
no error from input system
^
Wdym. I have said that when I press L on keyboard it works normally , so its bound right ?
SO what exactly did you put as the control path for L
You mean in game what happens or the component path?
the component path has the menu for listen to keybind
so its automatic
one question - how are you setting up your code that listens for inputs?
you mean the reaction method?
inputaction.performed += performedMethod
.canceled += SkipIACanceled;
Help, I am implementing the new VIVE OpenXR Plugin Windows, in a Unity 2021.3.25f1 project with a Vive Pro device, the hand detection works perfectly, but now I can't find information on how to manipulate the hand gestures and implement functions in unity. Does anyone have information on how to do this, in the VIVE OpenXR Plugin Windows v1.0.13 documentation there is no information on how to implement it.
@austere grotto it registeres as a 'keyboard1(onscreen)' but it doesnt register as 'Keyboard'. Does this help in any way?
I'm not really sure what this means
did you set up control schemes
I think it's just being registered as a second keyboard basically
and maybe that's why PlayerInput won't detect it
because it thinks it's a second player
I dont have any control schemes, ill try add one
Holy shit.... @austere grotto
I almost want was sent to mental hospital.
I created control scheme. I test it . It works.
I run it again. Now i cant even click any button on screen. Its like every button in broken. Wtf is happenign everything worked just now.
I tried messing around with player input component changing default map or auto switch. Sometimes I though it was working sometimes it didn't.
Someone is knocking at my door, no... its just unity giving me a headache...and halucinations...
Not only that I was duplicating an button on screen or removing it and the buttons started working again...
Then i restart and they don't work again. Sometimes deleting and and duplicating random object repaired all buttons... (or same button multiple times duplicating, so it wasn't covered)
At this point I am starting to see dragons in my room, talking to me and trying to tell me to stop the development.
At the end I go back to normal scene. It doesn't work again. I go back to the scene it was working a second ago. It's f.
I am downgrading to 2021 LTS
I set up the input system.
On pressed works, on released doesn't.
I rebind the controls to the exact same things(still in play mode)
Both work
I stop play mode and start it again (Input Actions asset same as when I stopped play mode)
On released doesn't work again
I fucking hate the new input system
What the hell did I do wrong
This is the input actions asset
@tame oracle ok im back
to check whether u have the gamepad attached, to play safe, we validate it in two way
make sure u have a gamepad attached to pc and unity can detect it
open the script u have, u should have these already
public void OnDeviceLost()
{
if(mouse == null)
{
Debug.Log("mouse is not connected!");
}
if(keyboard == null)
{
Debug.Log("keyboard is not connected!");
}
}
public void OnDeviceRegained()
{
Debug.Log("device reconnected!");
}
private void OnEnable()
{
playerMap.Enable();
}
private void OnDisable()
{
playerMap.Disable();
}```
note that these four function is intrinsic functions that is with the new input system or unity monobehaviour itself
OnDeviceLost u can do gamepad instead, dont just copy the code
private Gamepad gamePad;
private void Awake()
{
gamePad = Gamepad.current;
if(gamePad == null)
{
Debug.LogError("GamePad is not connected ! ");
}
}```
make sure u have this to check if gamepad connected during runtime
Hello every one,
I've just look at the local multiplayer tutotrial of Samyam. All is working great but as the control with a keyboard+Mouse is different with gamepad, I would like to detect the kind of controller in use (so if it is a keyboard or a gamepad). Could you please tell me how to do that ?
If the player1 is using a keyboard, do this
else if it a gamepad do this
I've seen that in the "Player Input" Component, we have "Control Scheme" and "Devices"
So I tried "GetComponent<PlayerInput>().devices" and "GetComponent<PlayerInput>().controlScheme"
But I 've got a error : "ArgumentException: GetComponent requires that the requested component 'PlayerInput' derives from MonoBehaviour or Component or is an interface."
Anyone have a solution please ?
Hello so everytime i press play then stop the script attached to the Event system goes missing
and i get this error
SerializedObjectNotCreatableException: Object at index 0 is null
this is after i stop play button
Okay I have a problem. I helped a friend migrate to the input system (as opposed to previously they were using Input.GetKey and other methods). We have movement bound both to left stick and to WASD, however the WASD input causes the character to instantly snap to a direction whenever they rotate, whereas the joystick works fine and delivers smooth movement (which makes sense keyboard input lacks pressure). Somehow, Input.GetAxis magically solves this and applies motion smoothing to keyboard inputs. How do I make it so that joystick and keyboard movement are similar in the least complex way possible using the input system.
GetAxis has built in smoothing yes
the new input system doesn't have it built in
but it's very easy to replicate
float horizontalInput = 0;
float gravity = 2; // similar to the "gravity" setting in the old input manager
void Update() {
float current = myInputAction.ReadValue<float>();
horizontalInput = Mathf.MoveTowards(horizontalInput, current, gravity * Time.deltaTime);
}```
if you are event based or using PlayerInput then something like:
float horizontalInput = 0;
float gravity = 2; // similar to the "gravity" setting in the old input manager
float currentInput;
void Update() {
horizontalInput = Mathf.MoveTowards(horizontalInput, currentInput, gravity * Time.deltaTime);
}
void OnMove(InputValue iv) {
currentInput = iv.ReadValue<float>();
}```
You are a godsend thanks
How to recreate this on new Input System Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out RaycastHit hit, 100f, layerMask.value))
In short: old system when aiming shoot Raycast and set target for AimIK in this position
so when I press right mouse button its shoot Raycast in Input.mousePosition
In InputManager i allready add this
// Aim
aimAction = currentMap.FindAction("Aim");
aimAction.performed += onAim;
aimAction.canceled += onAim;
private void onAim(InputAction.CallbackContext context)
{
IsAiming = context.ReadValueAsButton();
playerController.AimHandle(IsAiming);
}```
i pressed the button while falling asleep
WTF
and it held 4min
hello everyone i have a problem with a FPS controller camera using the new input system
using UnityEngine.InputSystem;
public sealed class CameraConrols : MonoBehaviour
{
public float _mouse_x_sens;
public float _mouse_y_sens;
public float _controller_sens;
void Awake()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Confined;
}
Vector2 _mouse_look = new Vector2();
[SerializeField] Transform _player_transform;
public void OnMouseLook(InputAction.CallbackContext context)
{
_mouse_look.x = _mouse_y_sens * context.ReadValue<Vector2>().x * Time.deltaTime;
_mouse_look.y -= _mouse_x_sens * context.ReadValue<Vector2>().y * Time.deltaTime;
transform.localRotation = Quaternion.Euler(_mouse_look.y, 0, 0);
_player_transform.Rotate(Vector3.up * _mouse_look.x);
}
public void OnControllerLook(InputAction.CallbackContext context)
{
_mouse_look.x = _mouse_y_sens * context.ReadValue<Vector2>().x * Time.deltaTime;
_mouse_look.y -= _mouse_x_sens * context.ReadValue<Vector2>().y * Time.deltaTime;
transform.localRotation = Quaternion.Euler(_mouse_look.y, 0, 0);
_player_transform.Rotate(Vector3.up * _mouse_look.x);
}
}``` this is my current implementation
The camera only moves a little bit each time i move the right stick on the Controller my mouse works fine
This unity button works just fine when in screen space positioning, but when turned into world space positioning, the game does not register the button press, or even react to a mouse over.
It is placed the highest on the hierarchy (ui, highest tier), and has a level 10 on hierarchy.
Someone has an idea please ?
Having trouble myself too, why do you want to access devices?
To detect if the input device is a gamepad or keyboard (as the control script has to be a littlebit different due to mouse vs stick aim)
can I see the actual code for this? As far as I know GetComponent should work with PlayerInput
PlayerInput literally extends MonoBehavior
Also, you might be able to use the OnControlsChanged or OnDeviceRegained callbacks to set a variable in your script. I'm not sure what they do exactly though, I was trying to find out but the documentation is actually horrid for the input system.
@livid glade
I found the problem. I had another element in my project named the same way and when I used VS Code autocomplete, it returned the wrong element (the one I shouldn't have called "PlayerInput").
So either I changed the name or I used "GetComponent<UnityEngine.InputSystem.PlayerInput>().currentControlScheme" which references the correct "PlayerInput" component.
Why, VS Code autocomplete with the wrong "PlayerInput", I don't know. I'm using Linux and have some issues to make autocompletion working so maybe it's not resolve completly.
don't crosspost. This has nothing to do with the input system either
mb sorry
now a input-system question : I wrote the code for the PlayerController.cs but my character still doesn't move, why?
I guess there's a bug in your code
or you set something up incorrectly in the editor
Without any details from you, impossible to say more
What can I send you to fix this?
https://hatebin.com/pqfpcebeqk
here is the code of Player Controller.cs so , i run the game but my player doesn't move
you're not doing anything in this script that would move any object
oh
this is also a #💻┃code-beginner question
unless you[re specifically having a problem with the input handling
ok im sorry
I just upgraded to unity LTS 2022.3.6f1 (windows), and am noticing that InputSystemUIInputModule no longer compiles. Inside InputSystemUIInputModule.cs (which is a cached package script) I'm noticing these compiler flags, which I'm guessing are no longer set (and setting UNITY_INPUT_SYSTEM_ENABLE_UI manually doesn't seem to do anything, not exactly sure why):
#if PACKAGE_DOCS_GENERATION || UNITY_INPUT_SYSTEM_ENABLE_UI
Anyone else having this issue? Looks like a bug with the latest LTS. If I go ahead and remove the broken script > add the standalone input module > replace with new input system, it will add the input system input module but it will break as soon as I enter play mode with the warning: The referenced script (Unknown) on this Behaviour is missing!
EDIT: looks like this is the same issue: https://forum.unity.com/threads/unity-new-input-system-multiplayereventsystem-and-inputsystemuiinputmodule-is-commented-out.885214/
could be a bug where the compiler defines aren't being set properly...
are all of your packages up to date?
Yes they are. Downgrading to 2022.5 didn't help. I'll try going back to a previous commit eventually but I'm not in the mood to do QA work for Unity for free at the moment lol.
Does anyone else have issues with the Input System UI Input Module occasionally dropping navigation inputs?
Sometimes I have to press the key multiple times before it moves the selection to the next button.
- I made a brand new project using 2021.3.29 LTS
- Installed Input System 1.6.3 and switched the input handling to use it
- Added a canvas with an Event System, Input System UI Input Module, and some buttons
- Set the First Selected button on the Event System
When I enter play mode and use W and S to change the selected button, it occasionally just drops the input and doesn't change the selection
It seems to be related to having a (ps4) controller connected. The input system will read the input event from the keyboard, but sometimes another (0, 0) input event will come in from the controller and overwrite the keyboard input before it has actually been processed by the input system.
Is there a way to find out what binding on an action is currently being used, like if you had a camera look action, that was binded to mouse delta and right stick, how would you detect if the gamepad was currently in use?
I'm getting some unexpected behavior using IPointerEnterHandler/IPointerEnterHandler on an object with a BoxCollider2D Collider. It seems to trigger both OnPointerEnter and OnPointerExit whenever my mouse enters or exits. Increasing the Edge Radius made the distance between Enter and Exit bigger, but it still triggers both before my pointer is over the object. Is there some other Collider that makes a "filled" rectangle rather than just the outline of a rectangle?
BoxCOllider2d is filled
are you perhaps displayinga ui element over it or something>?
I plan to, but right now I'm just Logging
Are you sure it's filled? It sure looks like an outline when you select it
EdgeCollider is the only non filled collider
or a tilemap collder in edges mode
Hmmm weird. Would spriteRenderers also block it? or just ui?
only colliders or ui graphics
Ahh thats it, there was an invisible object on the same square that had a collider, and of course the 2 sprites were the exact same size. Thanks for the help!
Hello, I was just experimenting with the new Input System when I noticed something weird: When I added a new Action to my Input Action Asset, I can select many control types (when action type is value). However, when I click on another action and then check again the previous action, those control types are just gone!
Here are some screenshots:
I just wanna know if it is normal for this to happen
So Im trying this new input system out. I generated my Input Action Set, I added input mappings to it, and hit the "generate C# code" button to generate the classes+structs.
How do I actually subscribe to its events inside of C# code (not via the drag and drop interface as my classes are not monobehaviors, but POCOs)
I can have a serialized field ref to an InputActionAsset but thats the generic one, which doesnt seem to have my actual generated input events on it
Nah is there a way to do it without the whole player input thing
Im looking for lower level hooking in
unity event , but its limited and still need coding
normally for advanced movement u need to invoke C#
nah not unity events either, there appears to be this interface I can implement and inject?
aight then idk honestly
the generated code has this interface:
public interface IGameplayActions
{
void OnMove(InputAction.CallbackContext context);
void OnPauseAttack(InputAction.CallbackContext context);
void OnAbility1(InputAction.CallbackContext context);
void OnAbility2(InputAction.CallbackContext context);
void OnAbility3(InputAction.CallbackContext context);
void OnGuard(InputAction.CallbackContext context);
void OnMouse(InputAction.CallbackContext context);
}
Which are all my methods
thats on the GameplayActions struct
im not those devs that obcessed with professional structures or concepts lmao
and it has this method:
public void AddCallbacks(IGameplayActions instance)
So I presume I can just implement that interface but then I dunno how I get like... the "real" struct I should be calling that method on
I mean that interface looks right, thats all my events with the callback contexts on it
boy this is really weirdly defined, its like nested inside of itself
major inversion of control has been done on this stuff so its extremely obfuscated on what is the actual "who owns who" you end up with by the end
No straight up the guide on the page is just different from what my code is generating, Im not seeing how I can drag and drop a ref to this POCO, because its just implementing 2 interfaces
What I have generated:
public partial class @InputActionSet: IInputActionCollection2, IDisposable
{
What they have in their example:
// MyPlayerControls is the C# class that has been generated for us.
// It encapsulates the data from the .inputactions asset we created
// and automatically looks up all the maps and actions for us.
MyPlayerControls controls;
Implying its a field they can serialize I guess?
oh wait
no wtf... they just new one up?
yeah okay, Ill try that, weird but... okay lol
Got it working with zenject, this is what I needed to do:
Registration:
var inputActionSet = new InputActionSet();
Container.BindInstance(inputActionSet);
Container.BindInterfacesTo<InputService>().AsSingle();
Container.BindInterfacesTo<GameplayActionService>().AsSingle();
Implementing Interface:
public class GameplayActionService : InputActionSet.IGameplayActions
{
// Just implement the interface, with dependency injection working fine!
}
Wiring events up:
public class InputService : IInputService, IInitializable
{
private InputActionSet Inputs { get; }
private InputActionSet.IGameplayActions GameplayActions { get; }
[Inject]
public InputService(
InputActionSet inputs,
InputActionSet.IGameplayActions gameplayActions
)
{
Inputs = inputs;
GameplayActions = gameplayActions;
}
public void Initialize()
{
Inputs.Gameplay.SetCallbacks(GameplayActions);
Inputs.Gameplay.Enable();
}
}
i need help
have problems using the new input system
AD on keyboard works fine but
WS is just moving my player up nd down instead of forward and backward
Those settings look right
whats your code in the event?
i was accidently changing y value instead of z
so its fixed now
but i have another problem 
nvm fixed
NullReferenceException while executing 'performed' callbacks of 'Player/Interact[/Keyboard/e]'
GameInput.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameInput : MonoBehaviour
{
public event EventHandler OnInteractAction;
private PlayerInputActions playerInputActions;
private void Awake()
{
playerInputActions = new PlayerInputActions();
playerInputActions.Player.Enable();
playerInputActions.Player.Interact.performed += Interact_performed;
}
private void Interact_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
{
OnInteractAction?.Invoke(this, EventArgs.Empty);
}
public Vector2 GetMovementVectorNormalized()
{
Vector2 inputVector = playerInputActions.Player.Move.ReadValue<Vector2>();
inputVector = inputVector.normalized;
return inputVector;
}
}
need help finding out how to fix
player.cs
You need to show the full error
It will have the exact filename and line number of the error
NullReferenceException while executing 'performed' callbacks of 'Player/Interact[/Keyboard/e]' UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*) UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)
it doesn't
That's the full error? Doesn't seem like it's even getting to your code
it is
wait theres this too
NullReferenceException: Object reference not set to an instance of an object ClearCounter.Interact (Player player) (at Assets/Scripts/ClearCounter.cs:17) Player.GameInput_OnInteractAction (System.Object sender, System.EventArgs e) (at Assets/Scripts/Player.cs:45) GameInput.Interact_performed (UnityEngine.InputSystem.InputAction+CallbackContext obj) (at Assets/Scripts/GameInput.cs:23) UnityEngine.InputSystem.Utilities.DelegateHelpers.InvokeCallbacksSafe[TValue] (UnityEngine.InputSystem.Utilities.CallbackArray1[System.Action1[TValue]]& callbacks, TValue argument, System.String callbackName, System.Object context) (at ./Library/PackageCache/com.unity.inputsystem@1.6.3/InputSystem/Utilities/DelegateHelpers.cs:46) UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*) UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
there's this
Transform kitchenObjectTransform = Instantiate(kitchenObjectSO.prefab, counterTopPoint);
idk what's wrong with it though
Just kitchenObjectSO probably
wdym
Not sure what's unclear about that
Your script may be on multiple objects
On one, you assigned the fields
On another, you didn't
I assigned it on all
it's a scriptable object
all of the scriptable objects have the prefab field set
me personally I think the error does lie
add some logs to:
Assets/Scripts/ClearCounter.cs:17
k
you'll be wrong 😉
log everything right before that loine
see what's null
something will be
errors lie a lot in c++ atleast lol
never
in c++ errors are horrible
It's always human error
yeah im not saying it is
but what if it was 🤨
then the engine would be lying
what
why does it say nothing
not even null
wtf
i have these debug.logs and its not saying anything
you put the logs in the wrong spot
they need to go BEFORE the error happens
none of your code after the error will run
still doesn't say anything
doesnt say anything
show your new code
and make sure you saved it
and if it still says nothing then that code isn't even running
`if (kitchenObject == null)
{
Debug.Log(kitchenObjectSO.prefab);
Debug.Log(counterTopPoint);
Transform kitchenObjectTransform = Instantiate(kitchenObjectSO.prefab, counterTopPoint);
kitchenObjectTransform.GetComponent<KitchenObject>().SetKitchenObjectParent(this);`
yes
show a screenshot of your console
but no logs
and also is this the right line?
^
something is very wrong with those two warnings
is this script actually attached?
yes
you have broken script references it seems
ok what the hell
so two things here:
- broken script references need to be resolved
- Make sure you put the logs in the right place
I have a question for the pro's ... I seem to have a little bit of accuracy issues with nav mesh.. here's my question , what's better A* or nav mesh?
Kind of apples and oranges. A* is a general purpose graph based pathfinding algorithm.
Navmesh is a bespoke Unity tool, which might even use A* under the hood in some capacity.
Unless you're asking about a very specific thing like Aron Granberg's "A* Pathfinding Project" Unity asset?
No just in general. Using it for indoor navigation system for my job. And the nav mesh like to indicate it's reached the target but there can be a wall between the user object and target.. nav mesh doesn't seem to wanna walk around objects sometimes
I'm also using pro builder , thought A* would work with the grid system in pro builder
In order to use A* you will need to somehow convert your 3D space into a graph or grid data structure to run the alogorithm over. Depending on how your game works this may be easy or hard
Hello, why is Callback cancelled not called on actiontype value with vector2 when releasing the mouse? I red sth about it being a bug...
Canceled is only called when i tap outside the game window, which is not how it should work
Should be - can you show how you hooked your code up?
wait actually - sorry if you bound osmething to the mouse position that's different from a mouse click
mouse click would be a button action, not a value/vector2
mouse position is totally different
if you want to klnow when the mouse is released you would bind it to the mouse button, not the mouse position
@austere grotto i want to tap, then move the mouse, then release
thats why i used vector2 bc i need the position of the taps and movement
those are two separate actions though
but this kind of sounds like a UI/event system kind of interaction
I would recommend using that instead of directly processing input
e.g. IPointerDownHandler
IBeginDragHandler
IDragHandler etc
i know what you mean but this isnt for UI Interaction 🙂
it woprks for non ui as well
as long as you:
- put colliders on the object(s)
- have an event system in the scene
- Have a Physics Raycaster on your camera
this is easy enough to do, you just need two actions though - the position and the mouse button separately
very easy to combine them
which one is for releasing? i tried button and release, but this is only called when i only tap without moving, so thats wrong
button, no interactions or processors, bound to mouse button 0 (or whichever mouse button)
listen for the canceled event
but^
alright, will give it a go. one minute
its drawing with the mouse/touchscreen in AR, i have one version which kinda works but is not what i really need
and the current version would work if the cancelled would be called
cancelled will be called
if you set up the button properly
just a simple button action
tied to the mouse button
and listen for the cancel event
ok one sec
if not working - show the details of what you tried
@austere grottothe button action type is only called if i dont move the mouse at all
show how you set things up
you keep just telling me that
and not showing anything
I can't help without seeing details
ok should go into dm?
no
Looks like you're trying to use the same action for moving and clicking
that;s not going to work
as mentioned, make a separate action for the position or delta of the mouse, and a separate one for the button
what is tapMoveReference?
Which action is that bound to
move is touchPosition with vector2
wdym "move"?
you only have something here called tapMoveReference
presumably that is referring to either TouchPress or TouchPosition
you will need two references
tapReference and touchPositionReference
yes, touchPositionReference would be action type value with vector2
what should i use for the tap?
you probably want "Primary Touch / press" NOT "PrimaryTouch / Tap"
Tap is literally to detect a tap interaction
aka the quick press thing
yeap
this wont normalize diagonal movement is that normal?
imagining the code something like this:
void OnEnable() {
touchPressRef.action.started += OnTouchOrRelease;
touchPressRef.action.canceled += OnTouchOrRelease;
}
void Update() {
if (isDrawing) {
touchPos = touchPosRef.action.ReadValue<Vector2>();
// continue drawing the line
}
}
void OnTouchOrRelease(CallbackContext ctx) {
if (ctx.started) {
isDrawing = rtue;
// start new line
}
else if (ctx.canceled) {
isDrawing = false;
// end the current line
}
}```
i think thats it, after releasing, cancelled gets called
yeah exactly
it should normalize it
instead of update i would use action.performed
is there a reason you did a composite binding for this though?
why not just bind it directly to Left Stick
you don't need a composite
that's probably breaking it somewhat
im confused, does that mean use stick instead of composite type 2d vector
Walk - Action type: Value, Control Type: Vector2
Binding - Left Stick [Switch Pro]
or wait thats control type
@austere grottothank you for helping. Should work now. Not a fan of the new input system. I still think it doesnt make sense that cancelled of value vector2 isnt called. That definetly shouldnt work like that
you bound it to a position vector
what should the "cancelled" state of touch position be?
when the position is the bottom left corner? (0,0)
idk, but it is an option which i can chose from 😅
I think maybe what you really wanted to do here was to work with EnhancedTouch: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Touch.html#enhancedtouchtouch-class
It gives you this Touch API that is more similar to the old input system Touch:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.EnhancedTouch.Touch.html
i did at first but needed to change it because it wouldnt call phase.began and ended
which was really confusing bc it worked in one script, but not the other, thats why i tried to use the input actions
need to look into it a bit more
again, thanks for taking your time
have a nice day 🙂
hmm still wont normalize the diags. and the left stick zones for switch seems way off, it goes diagonal when im holding straight left.
im reading the value directly and it never reaches 1
(on the diagonals)
if you remove the normalize processor what do you see
float values between -1 and 1. With it the 4 regular directions get normalized but the diagonals still use floats.
Forgot to @
normalized doesn't mean not using floats
it just means the vector will be of length 1
maybe you're misunderstanding what normalizing a vector means
Which means it should read as 1 0 -1 values only right?
no
a normalized vector is any vector on the unit circle
it basically means you will either be at 0,0 or full tilt
no partial tilting
these d1 and d2 are normalized, for example
because their length is 1
anything inside or outside the circle is not normalized
(1, 0) and (.707, .707) are both normalized vectors
(.5, 0) and (.5, .5) are not
Ohh, okay they is there a way to force the .707 value on diagonal holding.
Yeah
probably something like:
Vector2 input = whatever;
int segments = 8;
float degreesPerSegment = 360f / segments;
float angle = Mathf.Atan2(input.y, input.x) * Mathf.Rad2Deg;
angle -= degreesPerSegment / 2f;
angle /= degreesPerSegment;
angle = Mathf.RoundToInt(angle);
angle *= degreesPerSegment;
angle += degreesPerSegment / 2f;
input = Quaternion.Euler(0, 0, degreesPerSegment) * Vector2.right;```
The dpad reads it properly, do you know of a way to make the leftstick read as a dpad?
yeah the code I just wrote
this doesnt seem to work for wasd, is anything obviously wrong?
Hey everyone!
Can someone tell how I can "exclude" modifier?
I have a case where I have a composite Shift + 1. However I also have a 1 input. I want the single 1 input only to be performed if no modifier is used at all. Otherwise I have two input actions being performed.
Any how to do this?
Unity Muse tells me this:
noModifierAction = new InputAction();
noModifierAction.AddCompositeBinding("ButtonWithOneModifier")
.With("Button", "/1")
.With("Modifier", "None");
noModifierAction.performed += _ => OnNoModifierAction();
noModifierAction.Enable();
But it does not work. Is None a valid value here intented to negate the modifier? Or is it just some "dreamed" stuff of Unity Muse 😄
The mouse delta vector in the new input system seems to be much faster than the previous GetAxis("Mouse X") and GetAxis("Mouse Y"). Is there a constant to scale it down to how it previously worked?
How are you using it? They're both in pixels afaik
Old:
float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime * XSens * 100;
float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime * YSens * 100;
New:
var lookAxis = GameInputManager.Actions.Player.Look.ReadValue<Vector2>() * new Vector2(XSens, YSens) * (Time.deltaTime * 100);
And this is being polled in update not by events
Both are wrong, neither should be scaling mouse by deltaTime. It is already a delta.
Oh shit, you're right just read the docs. I've beein using them wrong my whole life :(. I'd swear every tutorial did it like that when I was learning unity a couple of years ago.
It has been annoyingly proliferated by a lot of bad tutorials that are generally all copying eachothers' homework
Just searched for a famous tutorial on youtube, and event brackeys did it like that 😦 https://youtu.be/_QajrabyTJc?t=428
Thank you so much tho
But wait, doesn't that still mean that the new input system is faster than the old one?
I have no idea how you're testing it, are you comparing those values directly or are you just doing it via feel?
Well if we isolate the vectors themselves from both "equations" then they should be the same if both systems havent changed. But when actually playing the game it's not just a small difference that I can "feel", it's literally about 1000 times faster than the old one. Like I move the mouse a bit and the camera has a seizure.
I'm gonna compare the values right now and tell you the result: Old: (-175.00, 25.00) New: (-3500.00, 500.00)
Mouse X and Mouse Y are scaled by the Sensitivity factor which is 0.1 by default
and then they also seem to be scaled by 0.5 for some reason
The new input system is just reporting pixels
Yeah, rando 0.5 scaling
Does it mean that on non-windows platforms I need to omit the .5?
I have no idea, the input system is doing things properly without default scaling and without this random 0.5
k thanks, I'll guess I'd just adapt the game sensitivity to the new system
public void OnKeyPressed(InputAction.CallbackContext context)
{
Debug.Log($"{context.control.displayName} was pressed");
}
How do I get the specific key? I keep just getting ANY KEY
I'd rather not have to go in and assign every key to something that could be modular
what are you trying to do with this?
There's likely a better way
Uhhh so, I have a hotbar with a String of the Key assigned to it. and want to use the ability based off of that.
ok you're not gooing to like this but
you should make 12 input actions
hahah
that is by far the most supported and flexible approach here
shid.
Well. I was going to have to do the whole keyboard just about
this will also let you rebind
why do you need the whole keybaord
don't think of this as a keyboard
think of it as "Action bar Slot 0", "Action Bar Slot 1" etc
Essentially this
this is how e.g. World Of Warcraft does it
but this is a UI for assigning things to the keyboard
this is not a list of all actions in your game
this is the inverse
Could you elaborate a little please? im kinda confused
every key on this image is not a bindable action the game
only the colored things are
you don't need to make an action for every key on the keyboard
you only need actions for the things you can do in the game
basically your first and second screenshots are completely different things
This is how world of warcraft does it for their hotbars
excatly
you can have code that displays those bindings in the game too, no problem
but conceptually in your code, that's Action 0
the binding is separate
And i essentially can still Bind it to Q W etc from the start
But what im calling is, OnAction1(InputAction.CallbackContext context) { blah blah}
exactly
Hey
https://i.gyazo.com/0abdb9a6068f93d2938bace39f58b447.png
Main camera script
public void OnDrag(InputAction.CallbackContext ctx)
{
if (ctx.started) _origin = GetMousePosition;
_isDragging = ctx.started || ctx.performed;
}
private void LateUpdate()
{
if (!_isDragging) return;
_difference = GetMousePosition - transform.position;
transform.position = new Vector3(_origin.x - _difference.x, transform.position.y, transform.position.z);
}
private Vector3 GetMousePosition => _mainCamera.ScreenToWorldPoint((Vector3)Mouse.current.position.ReadValue());
How can I add touch support with this type of script?
Is there a way to detect that?
Is the above code even proper?
Do I need to check for mouse position or do I check for input position somehow?
public void OnHotBarAction1(InputAction.CallbackContext context)
{
if (context.started)
{
PlayerCombatSystem.UseAbility(HotBarManager.Instance.HotBarSlots[0].ability);
}
}
@austere grotto So you think this is still the way huh?
@lethal kayak No off-topic media, please
yes - though I would probably just consolidate it all to one function which takes an int param more or less
hotBarAction1.performed += ctx => PerformHotbarAction(1);```
for some reason wasd doesnt work with my controls,. Heres how its set up. I cant find other people with this problem not sure whats wrong with it, my keyboard works with the start button (bound to enter) for example but wasd wont control the leftstick vector2.
the sticks control the script just fine as well
if you remove the switch binding does it work
no it doesnt
also after some testing nothing works with keyboard after the main menu, I can press the enter button to start the game but after that the keyboard is borked
cant you just make a dictionary?
public delegate void HotbarAction;
Dictionary<KeyCode, HotbarAction> keyCodeLookupAction
Then you can iterate through this dictionary on update. You dont need to copy/paste the code 12 times.
if you want to change the keybinding of a HotbarAction to something else, just change the key of the HotbarAction to the new KeyCode.
How is this implemented, in Update or?
I have one question - how would you typically implement wasd with ability to press shift to speed up, or control to slow down - w, a, s, d, shift and ctrl being separate inputs or there's better way?
wasd being one input action. ctrl and shift as separate ones
one with up/down/left/right composite I think is what they want
I'm pretty sure they want to know how to do that
IDK how to interpret the question really, but the composite was implied in my answer
its just in the plus menu next to the control
well yeah, but I think they didn't know that existed, so they probably wouldn't realize you were implying anything at all
Essentially, you just have to have a keybind with an action type of value and a control type of vector 2, go to the add menu and click on up/down/left/right composite, then put in the ones you want for each individual axis. Then use ReadValue<Vector2>() to get the value
And yes, the combined form is preferred and easier to manage
yeah, that's what I have so far - and I assume now modifier actions would be a separate (value - button) action?
what I would do is just make it a separate button and depending on the one you press, it modifies your speed value
i dont think it being a modifier would be very useful, but it might be in your scenario
something like this basically
yeah
thanks, I'm starting to learn how new system works so it's nice to have something to experiment around with and expand from already 😄
np, im still figuring it out too lol
in fact i literally was about to ask a question of my own lmao
i already have it typed out and ready to go
Voila, here it is:
I'm trying to get the direction from the player to the cursor so that I can fire a projectile, but for some reason ScreenToWorldPoint is returning zero (or more accurately, the camera's position)?
Essentially, I have a camera that slowly follows the player and the raw position of the mouse is accurate. But after putting it through ScreenToWorldPoint, it's returning zero and has no velocity before moving, but then shoots backwards towards the camera's position after moving. When the camera catches back up and overlaps the player perfectly, it still shoots backwards.
This is exactly what I did with the old input system (if I'm not mistaken), but this doesn't seem to be working? Any help or ideas would be appreciated.
Also, this is 2.5D, but I don't think that matters. The movement is all 2D across x and y.
Vector3 rawCursorPos = Mouse.current.position.ReadValue();
Vector3 playerPos = Player.players[1].transform.position;
Vector3 mouseDirection = Camera.main.ScreenToWorldPoint(rawCursorPos) - Player.players[1].transform.position;
mouseDirection.z = 0f;
(the code is part of the intialization for the projectiles' velocity, which never changes)
And I guess this might not even be an inputsystem issue, but i figure someone in this chat would probably know why
I can also send a video if anyone wants it
what kind of game is this?
first person?
third person?
top down?
2.5d top down
ok I wouldn't use Camera.ScreenToWorldPoint
so at an angle, but the core is 2d with 3d graphics
I would use Plane.Raycast here, with Camera.ScreenPointToRay
okay lol, ive only ever made 2d so that would make sense
e.g.
Plane worldPlane = new Plane(Vector3.up, Vector3.zero);
Ray r = Camera.main.ScreenPointToRay(rawCursorPos);
worldPlane.Raycast(r, out float enter);
Vector3 mouseWorldPos = r.GetPoint(enter);
Vector3 dirToMouse = mouseWorldPos - playerPos;```
okay, im gonna try this out one sec
Vector3.up would mean the plane uses x and z right? so x and y would be Vector3.forward?
yes
nvm this works great! just had to change to forward since i use x and y and set the z value to zero afterwards
but yeah, you got the idea
yeah
thanks for the help though!
I thought it was my logic that wasn't working, so i spent like three hours banging my head against the wall lmao
this solution is actually amazing though, since even when i tilt my camera back and offset it, it still works flawlessly
Can i see the move map info on this action map. I cant get my wasd to work i would appreciate it.
Is this what you mean?
Yeah thats exactly what mine looks like and it doesnt work
It only accepts the controller input
Do you have them on separate control schemes or on the same one?
The same one. Im just putting every controller in a single actionmap
Up above what you have works though?
What was wrong with it when you tried it
Just didnt accept inputs?
Idr, but I'm pretty sure that controller overrides keyboard
unless im mistaken
have you tried unplugging your controller?
Yeah it still doesnt work
It only accepts keyboard input on the title screen
Once i switch to another scene it borks
Do you have them on different action maps?
Like wasd in a ui map then wasd in a gameplay map
Nope everything is on the same one
huh
Im not making it like a pseudostatemachine
Just controls on a controller map to inputs
Yeah it sucks ty for trying to help
np
it took me so long to set up my dual support, its just a pain lol
finally figured out that my switch pro controller just spazzes out lol
Okay wait now it works if i start the game with my controller turned off but it locks out the keyboard if i ever turn on the controller
Even if i turn it back off