Why is the input() making a prefix error? - c#

I've been coding a top down game and I wrote the basic movement scripts but on line 32 it states that I need a prefix at the end.
How can I fix this ?
Here is the error I get:
Assets\PlayerController.cs(32,71): error CS1003: Syntax error, ','
expected
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private Rigidbody2D rb;
private float x;
private float y;
private Vector2 input;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
GetInput();
}
private void FixedUpdate()
{
rb.velocity = input * moveSpeed;
}
private void GetInput()
{
Vector2 input = new Vector2(input.GetAxisRaw("Horizontal"), 0 input.GetAxisRaw("Vertical"));
input.x = x;
input.Normalize();
}
}

First of all, it is best to understand the similarities and differences between input.GetAxis() and input.GetAxisRaw(). There are two types of incoming parameters: Vertical: Get the value in the vertical direction. Horizontal: Get the value in the horizontal direction. The return value of input.GetAxis() is [-1, 1], and the return value of input.GetAxisRaw() with smooth transition function is {-1, 0, 1}
private void GetInput()
{
float move = Input.GetAxis("Horizontal");
if(move != 0){
Vector2 input = new Vector2(move * Time, rb.velocity.y);
}
}
Hope can help you

Related

How do remove speed decreasing after a jump that is used AddForce method (Unity)?

I'm starting to make my game and ran into a problem with movement. My movement is based on the new input system and .AddForce(). The problem is that when I jump, the character's speed drops after landing and then starts picking up again.
A Physic Material with a Dynamic Friction of 2 hangs on the player's Capsule Collider (if it affects the problem)
How to make the character move without slowing down?
Video demonstration (I hope you can see what the problem is).
Rigidbody and Player Mover settings.
Code (there is no more associated code):
using System;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class PlayerMover : MonoBehaviour
{
[SerializeField] private LayerMask _groundLayer = 6;
[SerializeField] private float _moveForce;
[SerializeField] private float _maxForce;
[SerializeField] private float _jumpForce;
[SerializeField] private float _mouseSensitivity;
private PlayerInput _input;
private Rigidbody _rb;
private CapsuleCollider _collider;
private Camera _camera;
private float _rotationX;
private const float MinAngle = -90f;
private const float MaxAngle = 90f;
private void Awake()
{
_input = new PlayerInput();
_rb = GetComponent<Rigidbody>();
_collider = GetComponent<CapsuleCollider>();
_camera = GetComponentInChildren<Camera>();
_rb.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
if (_groundLayer == gameObject.layer)
{
Debug.LogError("Сортувальний рівень гравця повинен відрізнятися від сортувального рівня землі!");
}
_input.Player.Jump.performed += context => Jump();
}
private void OnEnable()
{
_input.Enable();
}
private void OnDisable()
{
_input.Disable();
}
private void FixedUpdate()
{
Move();
}
private void LateUpdate()
{
Look();
}
private bool IsGrounded
{
get
{
var bottomCenterPoint = new Vector3(_collider.bounds.center.x, _collider.bounds.center.y,
_collider.bounds.center.z);
return Physics.CheckCapsule(_collider.bounds.center, bottomCenterPoint, _collider.bounds.size.x * 1.1f,
_groundLayer);
}
}
private Vector3 MovementVector
{
get
{
var cameraDirectionF = _camera.transform.forward;
var cameraDirectionR = _camera.transform.right;
cameraDirectionF.y = 0;
cameraDirectionR.y = 0;
cameraDirectionF = cameraDirectionF.normalized;
cameraDirectionR = cameraDirectionR.normalized;
var direction = _input.Player.Move.ReadValue<Vector2>();
return cameraDirectionF * direction.y + cameraDirectionR * direction.x;
}
}
private Vector2 MouseVector => _input.Player.Look.ReadValue<Vector2>() * _mouseSensitivity * Time.deltaTime;
private void Jump()
{
if (IsGrounded == false) return;
_rb.AddForce(new Vector3(0, _jumpForce, 0), ForceMode.Impulse);
}
private void Move()
{
_rb.AddForce(MovementVector * _moveForce, ForceMode.Impulse);
if (Math.Sqrt(Math.Pow(_rb.velocity.x, 2) + Math.Pow(_rb.velocity.z, 2)) < _maxForce) return;
var maxVelocity = _rb.velocity.normalized * _maxForce;
_rb.velocity = new Vector3(maxVelocity.x, _rb.velocity.y, maxVelocity.z);
}
private void Look()
{
_rotationX -= MouseVector.y;
_rotationX = Math.Clamp(_rotationX, MinAngle, MaxAngle);
_camera.transform.localEulerAngles = new Vector3(_rotationX, MouseVector.y, 0);
transform.Rotate(Vector3.up * MouseVector.x);
}
}
I tried changing the different .AddForce() values in the .Move() and .Jump() methods. Changed the value when assigning Vector3 to _rb.velocity in the .Move() method, where there is a check for the maximum allowable speed (without this check, .AddForce() will constantly increase the speed of movement).
I also thought that the problem was in the MovementVector property, but it is not so, it gives the correct values.
(The following statement is most likely incorrect)
In my opinion, after the jump, at the lowest point of the jump (almost near the ground), the character falls perpendicularly down and thus the speed is completely extinguished, so it needs to be regained.
Edit: I just modified the code to see the lowest velocity values in the console. Added the following: two variables and .Update(), one check in the MovementVector property, and changing the _flag in the .Jump() method.
private bool _flag;
private double _min = double.MaxValue;
private void Update()
{
if (!_flag) return;
var current = Math.Sqrt(Math.Pow(_rb.velocity.x, 2) + Math.Pow(_rb.velocity.z, 2));
if (current < _min) _min = current;
Debug.Log(_min);
}
ㅤ
private Vector3 MovementVector
{
get
{
....
var direction = _input.Player.Move.ReadValue<Vector2>();
if (direction.magnitude == 0)
{
_flag = false;
}
return cameraDirectionF * direction.y + cameraDirectionR * direction.x;
}
}
ㅤ
private void Jump()
{
_flag = true;
if (IsGrounded == false) return;
//_rb.AddForce(new Vector3(0, _jumpForce, 0), ForceMode.Impulse);
_rb.AddForce(transform.up * _jumpForce, ForceMode.Impulse);
}
Now, on landing, I will get accurate velocity values. With this, I noticed something, when changing _maxForce to a higher side, the landing velocity also changes. If for _maxForce equal to five the velocity dropped to zero, for _maxForce equal to 10 it drops already to 4, for _maxForce equal to 15 - to 9.
In Jump() Method you are adding the force of (0,_jumpforce,0) so this zeroes out the current movement. instead of zero you should addforce with the vector direction multiplied by jumpForce
Example:
_rb.AddForce(transform.up * _jumpForce, ForceMode.Impulse);
I hope this is fix works fine as per your requirement.

I just start to learn some unity tutorial and get stuck for some reason

I just start learn some unity tutorial and get stuck by the error " There is no argument given that corresponds to the required formal parameter 'direction' of 'My_Script.movePlayer(Vector3) "
And I dont know why?
public class My_Script : MonoBehaviour
{
public float speed = 10.0f;//movement speed
private Rigidbody rb;
public Vector3 movement;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
// Keyboard Input
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Jump");
float z = Input.GetAxis("Vertical");
movement = new Vector3(x, y, z);
}
private void Fixedupdate()
{
movePlayer();
}
void movePlayer(Vector3 direction)
{
rb.velocity = direction * speed;
}
}
Your function movePlayer(Vector3 direction) takes a parameter of type vector3, but when you call this function in FixedUpdate(), you forgot to give it this parameter. So you should write :
private void Fixedupdate()
{
movePlayer(movement);
}
This should solve your problem.
Every function which is non-parameterless accepts an argument.
So you will have to pass a Vector3 value inside the movePlayer function, like this:
movePlayer(movement) or something else of type Vector3

Diagonal movements are faster than normal movements

FIRST : SORRY FOR MY ENGLISH !!!
Hello everyone, i'm very new into Unity (5 days).
Today i've make a script for the basics movements with a rigid-bodie, BUT the diagonal movements are faster than the normal movements.. I search on Internet but I don't find a post that i can understand.
So here my script.
Also if you know how to not move when we jump, or when we jump into a direction, it follow this direction, tell me. (I know my english is terrible.) Also, i'm new into this website.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovements : MonoBehaviour
{
[SerializeField] private float walkingSpeed;
[SerializeField] private float runningSpeed;
[SerializeField] private float jumpForce;
[SerializeField] private float jumpRaycastDistance;
private Rigidbody rb;
float speed;
Vector3 movement;
/////////////////////////////////////////////////////
void Start()
{
rb = GetComponent<Rigidbody>();
}
/////////////////////////////////////////////////////
void Update()
{
Jumping();
}
/////////////////////////////////////////////////////
private void FixedUpdate()
{
Movements();
}
/////////////////////////////////////////////////////
private void Movements()
{
float hAxis = Input.GetAxisRaw("Horizontal");
float vAxis = Input.GetAxisRaw("Vertical");
if(Input.GetButton("Run"))
{
Vector3 movement = new Vector3(hAxis, 0, vAxis) * runningSpeed * Time.deltaTime;
Vector3 newPosition = rb.position + rb.transform.TransformDirection(movement);
rb.MovePosition(newPosition);
}
else
{
Vector3 movement = new Vector3(hAxis, 0, vAxis) * walkingSpeed * Time.deltaTime;
Vector3 newPosition = rb.position + rb.transform.TransformDirection(movement);
rb.MovePosition(newPosition);
}
}
/////////////////////////////////////////////////////
private void Jumping()
{
if(Input.GetButtonDown("Jump"))
{
if (isGrounded())
{
rb.AddForce(0, jumpForce, 0, ForceMode.Impulse);
}
}
}
/////////////////////////////////////////////////////
private bool isGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, jumpRaycastDistance);
}
}
You need to clamp your velocity in order to keep it same. Look into Vector3.ClampMagnitude()
velocity = Vector3.ClampMagnitude(velocity, _movementSpeed);
velocity.y = playerVelocity.Y; // keeping your Y velocity same since you have jumping.
playerVelocity = velocity;
EDIT: in your case it should be something like this.
_maxSpeed is the speed limit.
private void FixedUpdate()
{
Movements();
var clampedVelocity = Vector3.ClampMagnitude(rb.velocity, _maxSpeed);
clampedVelocity.y = rb.velocity.y;
rb.velocity = clampedVelocity;
}
Try normalizing the vector. (more info is on unity docs, but normalize() will make sure that the sum of all the vector's values isnt above 1.

How can I fix "Cannot read value of type Vector2 from composite" error in Unity?

I'm making a 2D game with Unity using the new Input System. I used spriteRenderer.flipX to flip the player but since it is made of three parts (body and two eyes), the spriteRenderer didn't work. Also, I couldn't convert them to a single sprite because I need the eyes in order to animate them. So, I decided to use transform.localscale for flipping and change movementInput value from a float to a Vector2. The problem is that when I press the arrow or AD keys to move the character, an error pops up saying "Cannot read value of type Vector2 from composite". This error is from InputActionState which is a long and complicated code related to the new Input System. Also, getting input from gamepad causes the same error. I don't know what does this error mean and how can I fix it. Now, the player can jump but it can't move or flip. You can see the code, the error and my action map down below.
This is my Player Controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float speed, jumpSpeed;
[SerializeField] private LayerMask ground;
private PlayerActionControls playerActionControls;
private Rigidbody2D rb;
private PolygonCollider2D pol;
private Animator animator;
private bool facingRight = true;
private Vector2 movementInput;
private void Awake() {
playerActionControls = new PlayerActionControls();
rb = GetComponent<Rigidbody2D>();
pol = GetComponent<PolygonCollider2D>();
animator = GetComponent<Animator>();
}
private void OnEnable() {
playerActionControls.Enable();
}
private void OnDisable() {
playerActionControls.Disable();
}
void Start()
{
playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue<float>());
}
private void Jump(float val) {
if (val == 1 && IsGrounded()) {
rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);
}
}
private bool IsGrounded() {
Vector2 topLeftPoint = transform.position;
topLeftPoint.x -= pol.bounds.extents.x;
topLeftPoint.y += pol.bounds.extents.y;
Vector2 bottomRightPoint = transform.position;
bottomRightPoint.x += pol.bounds.extents.x;
bottomRightPoint.y -= pol.bounds.extents.y;
return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
}
void FixedUpdate()
{
if(facingRight == false && movementInput.x > 0){
Flip();
} else if (facingRight == true && movementInput.x < 0){
Flip();
}
}
void Flip(){
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
void Update()
{
Vector2 movementInput = playerActionControls.Land.Move.ReadValue<Vector2>();
Vector2 currentPosition = transform.position; // This was a Vector3 but since I got the error "Operator '+=' is ambiguous on operands of type 'Vector3' and 'Vector2", I changed it to a Vector2.
currentPosition += movementInput * speed * Time.deltaTime;
transform.position = currentPosition;
}
}
This is the error I get when I want to move the player.
This is my action map.
I changed my action map to this and now the flipping is working and I don't get that error anymore.

Print Unity Coordinates to a string at specified time interval

I want to move a cube using some device and periodically (every 3 seconds) print those coordinates to a file. I am not sure how to accomplish this with my code below. Does anybody have ideas as to how this can be done?
Thank you!
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
[RequireComponent(typeof(MeshCollider))]
public class UserController : MonoBehaviour {
public int speed = 20;
// Update is called once per frame
void Update()
{
// get input data from keyboard or controller
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// update player position based on input
Vector3 position = transform.position;
position.x += moveHorizontal * speed * Time.deltaTime;
position.z += moveVertical * speed * Time.deltaTime;
transform.position = position;
}
void OnMouseDrag()
{
if(Input.GetMouseButton(0))
{
float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
}
}
}
I would suggest creating a separate script and attach it to your cube.
public class CubeTracker : MonoBehaviour
{
private bool logging = true;
void Awake()
{
StartCoroutine(LogPosition());
}
private IEnumerator LogPosition()
{
while (logging)
{
Debug.Log(transform.position);
yield return new WaitForSeconds(3f);
}
}
}
This will start a coroutine as soon as the cube is created and should log your desired result into console. If that's what you desire, you can then go ahead and replace the Debug.Log with a write-to-file implementation.
Use a global variable, and feed it inside Update() method.
for example:
private Vector3 LastCoordinate{get; set;}
and the use a periodic timer like :
private System.Threading.Timer timer;
timer = new System.Threading.Timer(GetLastCoordinate, null, 3000, 0);
private void GetLastCoordinate()
{
lock(this)
{
Vector3 lastCoordEachThreeSecs = LastCoordinate;
}
}

Categories