error with movement in unity following a tutorial - c#

i'm trying to make a game on unity using C# for a games dev course. the course is: https://www.youtube.com/watch?v=b8YUfee_pzc and at 51:55 is where i am experiencing the error. the error is NullReferenceException: Object reference not set to an instance of an object player.FixedUpdate () (at Assets/scripts/player.cs:32)
i have checked and it seems to be letter by letter (including caps) perfect, unless i'm jsut stupid.
it may be because of outdated code, something in unity or me just copying something down wrong. anyhow, here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class player : MonoBehaviour
{
private BoxCollider2D boxCollider;
private RaycastHit2D hit;
private Vector3 moveDelta;
private void start(){
boxCollider = GetComponent<BoxCollider2D>();
}
private void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
// reset move delta
moveDelta = new Vector3(x, y, 0);
// swap sprite direction
if(moveDelta.x > 0)
transform.localScale = Vector3.one;
else if (moveDelta.x < 0)
transform.localScale = new Vector3(-1,1,1);
hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(0, moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("actor", "blocking"));
if (hit.collider == null)
{
transform.Translate(0, moveDelta.y * Time.deltaTime, 0);
}
hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x, 0), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("actor", "blocking"));
if (hit.collider == null)
{
transform.Translate( moveDelta.x * Time.deltaTime, 0, 0);
}
}
}```

Found a comment on that video that worked for me: "changing "private BoxCollider2D boxCollider;" to "public BoxCollider2D boxCollider;" then dragging the box collider in to the tab on the script under your npc"

Related

How to fix the Unity C# error CS0117: 'UnityWebRequest' does not contain a definition for 'redirectLimit'?

I'm pretty new to Unity, and recently I've begun working on my first mobile game using C#, and suddenly I get the CS0117 error and I don't know why since my code is pretty simple and the console won't specify in which line the error occurs. I received the error when I wrote the simple line:
transform.position = new Vector3 (0, 0, 0);
in my player script to set it's position to the same as the position of the camera. I don't think that this has anything to do with the script itself, but that it is a problem with my phone, but I don't know what the problem is.
In case you need it, here are the full scripts of the player and the camera.
player script:
public class playerScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
transform.position = new Vector3 (0, 0, 0);
}
// Update is called once per frame
void Update()
{
//movement
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
touchPosition.z = 0f;
transform.position = touchPosition;
}
//borders
if (transform.position.x >= 2.3f)
{
transform.position = new Vector3(2.3f ,transform.position.y, 0);
}
if (transform.position.x <= -2.3f)
{
transform.position = new Vector3(-2.3f ,transform.position.y, 0);
}
if (transform.position.y >= 4.5f)
{
transform.position = new Vector3(transform.position.x, 4.5f, 0);
}
if (transform.position.y <= -4.5f)
{
transform.position = new Vector3(transform.position.x, -4.5f, 0);
}
}
}
Camera script:
public class cameraScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
transform.position = new Vector3 (0, 0, 0);
}
// Update is called once per frame
void Update()
{
}
}

Boxcast in Unity2d not working as intended

I'm currently trying to use a Physics2D.BoxCast() to manually detect collisions in a test project. I got everything set up with the help of a tutorial I watched a while ago but for some reason the box cast seems to be above the Box Collider that I attached its size to. I'm not the best a writing issues out so Ill have a gif bellow that better shows what the problem is, as well as I'll attach the code I used to detect the collisions.
This is when I try to collide from +y on the axis
This is when I try to collide from -y on the axis:
I've tried looking up more on how Physics2D.BoxCast work and why it would seem to be pushed down but I havent found anything helpful just yet.
Here's the code I use for movement and manual collision detection.
using UnityEngine;
public class Player : MonoBehaviour {
public float speed = 2f;
private BoxCollider2D boxCollider;
private SpriteRenderer sprite;
private Vector3 moveDelta;
private RaycastHit2D hit2D;
protected virtual void Awake() {
boxCollider = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
}
protected virtual void Update() {
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
moveDelta = new Vector3(x, y, 0);
// Flips the sprite based on the direction its moving on the X
if (moveDelta.x > 0)
{
sprite.flipX = false;
}
if (moveDelta.x < 0)
{
sprite.flipX = true;
}
// Manual detection for collisions
hit2D = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x, 0), Mathf.Abs(moveDelta.x * Time.deltaTime), LayerMask.GetMask("Blocking", "Actor"));
if (hit2D.collider == null)
{
transform.Translate(moveDelta.x * Time.deltaTime, 0, 0);
}
hit2D = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(0, moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("Blocking", "Actor"));
if (hit2D.collider == null)
{
transform.Translate(0, moveDelta.y * Time.deltaTime, 0);
}
}
}
The transform.position used in the box cast was not at the center of the collider. Thus casting the BoxCast above where the collider was. The solution was to place an empty game object in the center of the collider. Again I'm sorry about the way I explain things I hope the pictures bellow can help you understand better..
Code wise it was a simple fix that took me too long to figure out..
using UnityEngine;
public class Player : MonoBehaviour {
public float speed = 2f;
public GameObject boxcastCenter;
private BoxCollider2D boxCollider;
private SpriteRenderer sprite;
private Vector3 moveDelta;
private RaycastHit2D hit2D;
protected virtual void Awake() {
boxCollider = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
}
protected virtual void Update() {
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
moveDelta = new Vector3(x, y, 0);
// Flips the sprite based on the direction its moving on the X
if (moveDelta.x > 0)
{
sprite.flipX = false;
}
if (moveDelta.x < 0)
{
sprite.flipX = true;
}
// Manual detection for collisions changes were made in the transform.position bellow
hit2D = Physics2D.BoxCast(boxcastCenter.transform.position, boxCollider.size, 0, new Vector2(moveDelta.x, 0), Mathf.Abs(moveDelta.x * Time.deltaTime), LayerMask.GetMask("Blocking", "Actor"));
if (hit2D.collider == null)
{
transform.Translate(moveDelta.x * Time.deltaTime, 0, 0);
}
hit2D = Physics2D.BoxCast(boxcastCenter.transform.position, boxCollider.size, 0, new Vector2(0, moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("Blocking", "Actor"));
if (hit2D.collider == null)
{
transform.Translate(0, moveDelta.y * Time.deltaTime, 0);
}
}
}

2D Movement Bug in Unity

I'm trying to make a 2D Space Shooter game in Unity but stumbled upon a bug that needs fixing. I'm using Unity 2021.1.0f1 and the new Input System in Unity and I'm trying to implement movement for my character. When I press the WASD keys, my character for some reason moves 15 units on every press. I don't want that, I want smooth movement for my character. Here's my code:
using UnityEngine;
using UnityEngine.InputSystem;
public class Ship : MonoBehaviour
{
private Keyboard _keyboard = Keyboard.current;
[SerializeField] private float speed = 0.25f;
[SerializeField] private GameObject projectile;
[SerializeField] private Rigidbody2D rigidbody;
private void Start()
{
if (speed == null)
{
Debug.Log("Please assign a a value to \"speed\".");
}
if (rigidbody == null)
{
Debug.Log("Please assign a a value to \"rigidbody\".");
}
if (projectile == null)
{
Debug.Log("Please assign a a value to \"projectile\".");
}
}
public void OnMove(InputAction.CallbackContext context)
{
Vector2 movementVector = context.ReadValue<Vector2>();
Vector3 move = Quaternion.Euler(0.0f, transform.eulerAngles.y, 0.0f) * new Vector3(movementVector.x, movementVector.y, 0.0f);
transform.position += move * speed;
}
public void OnFire(InputAction.CallbackContext context)
{
Vector2 spawnPosition = new Vector2(transform.position.x, 0.5f);
if (context.performed)
{
Instantiate(projectile, spawnPosition, Quaternion.identity);
}
}
}
Anyone?
I have been working on the same project lately and I used the following code for the movement of my spaceship and it moves smoothly :
void C_Movement(){
//Input controller (direction)
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical") ;
Vector3 directionX = new Vector3(horizontalInput,0,0) ;
transform.Translate(directionX* Time.deltaTime * 13) ;
Vector3 directionY = new Vector3(0,verticalInput,0) ;
transform.Translate(directionY* Time.deltaTime * 13) ;
}

When I want my Player to jump he is flying (Unity2d)

Hello I want to make my first game in 2D but when i want to Jump, my Player is flying and he doesnt come back to the ground. I don't know why it doesnt work. Hopefully someone can help me. Thank you. Here is my Code:
using UnityEngine;
using System.Collections;
public class Move2D : MonoBehaviour
{
public float speed = 5f;
public float jumpSpeed = 8f;
private float movement = 0f;
private Rigidbody2D rigidBody;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movement = Input.GetAxis("Horizontal");
if (movement > 0f)
{
rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
}
else if (movement < 0f)
{
rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
}
else
{
rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
}
if (Input.GetButtonDown("Jump"))
{
rigidBody.velocity = new Vector2(rigidBody.velocity.x, jumpSpeed);
}
}
}
You set the y velocity on jump but never set it back to anything else. I suggest that for jump you use rigidBody.AddForce:
rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);
I also have to say that your first if..else if...else seems to be redundant.
If movement > 0, you do X, is movement is < 0, you do exactly the same, and
if movement == 0, you still do the same even tho you write it differently. (If movement == 0 then movement * speed is also 0). So you could just state that
rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
without using if at all.
edit: I accidentally wrote wrong line for what to use, fixed it now.
edit2: So after both of these changes your Update function would be like:
void Update()
{
movement = Input.GetAxis("Horizontal");
rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
if (Input.GetButtonDown("Jump"))
{
rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);
}
}

Why won't my rigid body stop moving on collision?

I'm new to Unity.
Below is my simple character controller C# script. I'm using 3d cubes with box colliders and rigid bodies as both my walls and player. Currently when my player comes into contact with a wall, it just keeps going.
Why is my script not working?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour {
public float speed = 180;
private Rigidbody rig;
private Vector3 movement;
// Use this for initialization
void Start () {
rig = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate () {
if (rig.velocity.magnitude <= 0)
{
if (Input.GetKeyUp("up"))
rig.velocity = new Vector3(0, 0, rig.position.z * speed );
else if (Input.GetKeyUp("down"))
rig.velocity = new Vector3(0, 0, rig.position.z * speed * -1);
else if (Input.GetKeyUp("right"))
rig.velocity = new Vector3(rig.position.x * speed, 0, 0);
else if (Input.GetKeyUp("left"))
rig.velocity = new Vector3(rig.position.x * speed * -1, 0, 0);
}
}
void OnCollisionEnter(Collision collision)
{
rig.velocity = Vector3.zero;
}
}
The script above works... My y position was higher than the position of my walls so there was never any collision. I feel dumb. Leaving post up as a reminder of my failure.

Categories