Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Movement script not working properly

Discussion in '2D' started by Evwaldo, Mar 22, 2018.

  1. Evwaldo

    Evwaldo

    Joined:
    Mar 21, 2018
    Posts:
    4
    Hey all, I'm new to working with unity and have a movement script that's not working quite right. It allows the player to press the W key infinatly so they can keep jumping without touching the ground. When I try to change that I get an error with if (Collision.gameObject.tag == "ground"). It's the last void at the bottom. Any suggestions?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerController : MonoBehaviour
    {
    public float speed = 10;
    public float jumpHeight = 10;

    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool grounded;

    int JumpCount = 0;
    public int MaxJumps = 1;

    // Use this for initialization
    void Start()
    {
    JumpCount = MaxJumps;
    }
    private void fixedUpdate()
    {
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
    }
    // Update is called once per frame
    void Update()
    {

    if (Input.GetKey(KeyCode.W))
    {
    if (JumpCount > 0)
    {
    Jump();
    }
    }


    if (Input.GetKeyDown(KeyCode.W))
    {
    GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
    }

    if (Input.GetKey(KeyCode.D))
    {
    GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y);
    }

    if (Input.GetKey(KeyCode.A))
    {
    GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.y);
    }
    }
    public void Jump()
    {
    GetComponent<Rigidbody2D>().velocity = transform.up * 10;
    JumpCount -= 1;
    }
    void OnCollisionEnter2D(Collision2D Col)
    {
    if (Collision.gameObject.tag == "ground")
    {
    JumpCount = MaxJumps;
    }
    }
    }
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    "Collision" is the name of a class. You meant to use the variable that references Collision2D, which you named "Col".
    Also, it is standard convention in C# to start all variable names with a lowercase letter.