Unity accessing rigidBody component with input system - c#

I have just started a new Unity tut using its input system to move a ball. However, the script doesn't seem to be working when I try to move the ball
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem; //Namespace for accessing InputSystem to control ball
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
private float movementX;
private float movementY;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Onmove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement);
}
}

If you did everything else right and the problem is only in your script then changing from Onmove to OnMove should fix problem

Create in Unity a new InputControl with the name PlayerInputActions and into
Inspector select Generate C# class, Unity autogenerate for you Action Maps , Actions and Binding Property, double click on it to watch, than in a new c# script named NewInputSystem
using UnityEngine;
using UnityEngine.InputSystem;
public class NewInputSystem : MonoBehaviour
{
public Rigidbody rb;
public float moveSpeed = 7.0f;
Vector2 moveDirections = Vector2.zero;
public PlayerInputActions playerControls;
private InputAction move;
private void Awake()
{
playerControls = new PlayerInputActions();
}
private void OnEnable()
{
move = playerControls.Player.Move;
move.Enable();
}
private void OnDisable()
{
move.Disable();
}
void Start()
{
rb =gameObject.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
moveDirections = move.ReadValue<Vector2>();
}
private void FixedUpdate()
{
//change how you want
rb.velocity = new Vector3(moveDirections.y * moveSpeed, 0, moveDirections.x * -moveSpeed);
}
}

Related

Unity2d: the player stop moving when I add an animation

I have a problem in unity , the player mouvement is going good until I add an animation the player stop moving even if I press the keyboard keys,when I remove the animator compenent the player move normaly without problems !
I tried separate the animation script from the movement script and still theame problem , I don't think that the problem is comming from the code
playerAnimation code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerAnim : MonoBehaviour
{
Animator anim;
Rigidbody2D rb;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void FixedUpdate()
{
if (rb.velocity.x == 0)
anim.SetBool("isRunning", false);
else
anim.SetBool("isRunning", true);
if (rb.velocity.y > 0)
anim.SetBool("isJumping", true);
else
anim.SetBool("isJumping", false);
}
}
playerMovement script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerControl : MonoBehaviour
{
Rigidbody2D rb;
private float horizontal;
public float runSpeed;
public float jumpPower;
public bool inTheGround;
private SpriteRenderer sp;
Animator anim;
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
sp = gameObject.GetComponent<SpriteRenderer>();
anim = gameObject.GetComponent<Animator>();
}
private void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * runSpeed,
rb.velocity.y);
if (Input.GetButton("Jump")&& inTheGround)
{
rb.velocity = new Vector2(rb.velocity.x,jumpPower);
}
flipping();
Debug.Log(rb.velocity.x);
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("ground"))
inTheGround = true;
}
private void OnCollisionExit2D(Collision2D other)
{
if
(other.gameObject.CompareTag("ground")&&rb.velocity.y>0.1)
inTheGround = false;
}
void flipping()
{
if (Input.GetKey(KeyCode.RightArrow))
sp.flipX = false;
if (Input.GetKey(KeyCode.LeftArrow))
sp.flipX = true;
}
}
Check if Apply Root Motion on Animator Component is set to false. This setting can overwrite your changes of the object's position over time. if not - can you please provide more information, perfectly a screenshot of your player components, and Animator Controller.

C# Unity 2D Topdown Movement Script not working

I have been working on a unity project where the player controls a ship. I was following along with a tutorial and have made an input script and a movement script that are tied together with unity's event system. As far as I can tell my script and the script in the tutorial are the same, but the tutorial script functions and mine doesn't.
Script to get player input
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.Events;
public class PlayerInput : MonoBehaviour
{
public UnityEvent<Vector2> OnBoatMovement = new UnityEvent<Vector2>();
public UnityEvent OnShoot = new UnityEvent();
void Update()
{
BoatMovement();
Shoot();
}
private void Shoot()
{
if(Input.GetKey(KeyCode.F))
{
OnShoot?.Invoke();
}
}
private void BoatMovement()
{
Vector2 movementVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
OnBoatMovement?.Invoke(movementVector.normalized);
}
}
Script to move player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Movement : MonoBehaviour
{
public Rigidbody2D rb2d;
private Vector2 movementVector;
public float maxspeed = 10;
public float rotatespeed = 50;
private void Awake()
{
rb2d = GetComponent<Rigidbody2D>();
}
public void HandleShooting()
{
Debug.Log("Shooting");
}
public void Handlemovement(Vector2 movementVector)
{
this.movementVector = movementVector;
}
private void FixedUpdate()
{
rb2d.velocity = (Vector2)transform.up * movementVector.y * maxspeed * Time.deltaTime;
rb2d.MoveRotation(transform.rotation * Quaternion.Euler(0, 0, -movementVector.x * rotatespeed * Time.fixedDeltaTime));
}
}
Any help would be appreciated!
You need to attach your Handlers (HandleShooting and Handlemovement) to corresponding events. Easiest way would be to make events static in PlayerInput
public static UnityEvent<Vector2> OnBoatMovement = new UnityEvent<Vector2>();
public static UnityEvent OnShoot = new UnityEvent();
and attach corresponding handlers to them in Movement.Awake
private void Awake(){
rb2d = GetComponent<Rigidbody2D>();
PlayerInput.OnBoatMovement += Handlemovement;
PlayerInput.OnShoot += HandleShooting;
}
Also in PlayerInput.BoatMovement you should probably check
if(movementVector.sqrMagnitude > 0){
OnBoatMovement?.Invoke(movementVector.normalized);
}
Or else random shit may happen when trying to normalize Vector with magnitude 0 (I compare sqr magnitude to aviod calculating root which is never desired)

How to make sprites spawn in and disappear on screenbounds in unity

I'm trying to create a game where asteroids spawn in and despawn when touching a screenbound, I've looked at many tutorials but these doesn't work for me or say I got something wrong in the code while the code seems to be fine, how do I make it so they spawn in at random and despawn when they touch the screenbounds?
Code I got for now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class asteroid : MonoBehaviour
{
public float speed = 10.0f;
private Rigidbody2D rb;
private Vector2 screenBounds;
// Use this for initialization
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(0, -speed);
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void Update()
{
if (transform.position.y < screenBounds.y)
{
Destroy(this.gameObject);
}
}
}
Try to check if the Renderer component is visible:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class asteroid : MonoBehaviour
{
public float speed = 10.0f;
private Rigidbody2D rb;
private Vector2 screenBounds;
// Use this for initialization
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(0, -speed);
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void Update()
{
if (!GetComponent<Renderer>().isVisible)
{
Destroy(this.gameObject);
}
}
}
You can use this function:
void OnBecameInvisible()
{
Destroy(gameObject);
}

The name 'rb' does not exist in the current context?

I am pretty new to c# and unity, I decided to make a test game were you can control the player, the thing is I keep getting this error: 'The name 'rb' does not exist in the current context'. I have no clue what this means, but this is what I have done.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement_controller : MonoBehaviour
{
public float Speed = 1.0f;
void Awake()
{
rb = gameObject.AddComponent<Rigidbody2D>() as Rigidbody2D;
rb.bodyType = RigidbodyType2D.Kinematic;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W))
{
rb.velocity = (Speed, 0.0f);
}
}
}
You have to assign rb as a variable.
public float Speed = 1.0f;
private Rigidbody2D rb;
void Awake()
{
rb = gameObject.AddComponent<Rigidbody2D>() as Rigidbody2D;
rb.bodyType = RigidbodyType2D.Kinematic;
}
you have only called rb within the awake function, but you have not assigned it as a global variable.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement_controller : MonoBehaviour
{
public float Speed = 1.0f;
public RigidBody rb; //<====
void Awake()
{
rb = gameObject.AddComponent<Rigidbody2D>() as Rigidbody2D;
rb.bodyType = RigidbodyType2D.Kinematic;
}

how do i drag and launch in untiy 2d?

I am a newbie in c# and i have been trying to get some code that will help me launch my character in the opposite direction of the drag. Like Angry Birds but i don't want the character to move while i am dragging. Here is my script that i copied from a video and it isn't working.
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbMovement : MonoBehaviour
{
public float launchSpeed = 100;
Vector3 _initialPosition;
Rigidbody2D rb;
private Vector2 directionToInitialPosition;
private void Awake()
{
_initialPosition = transform.position;
rb = GetComponent<Rigidbody2D>();
directionToInitialPosition = _initialPosition - transform.position;
}
private void OnMouseUp()
{
rb.AddForce(directionToInitialPosition *launchSpeed);
}
private void OnMouseDrag()
{
Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(newPosition.x, newPosition.y);
}
}
`
help me with a script that will launch my character opposite of the drag. Thanks in advance :)
Why don't you just remove the
private void OnMouseDrag()
{
Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(newPosition.x, newPosition.y);
}
this part of the script means that everytime the player drag the mouse/touch then the gameobject will follow the mouse. Because you don't want it, you can just remove it to
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbMovement : MonoBehaviour
{
public float launchSpeed = 100;
Vector3 _initialPosition;
Rigidbody2D rb;
private Vector2 directionToInitialPosition;
private void Awake()
{
_initialPosition = transform.position;
rb = GetComponent<Rigidbody2D>();
directionToInitialPosition = _initialPosition - transform.position;
}
private void OnMouseUp()
{
rb.AddForce(directionToInitialPosition *launchSpeed);
}
}

Categories