Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Player script disables the bounciness of my character?

Discussion in '2D' started by Felixj93, Jul 2, 2020.

  1. Felixj93

    Felixj93

    Joined:
    May 2, 2020
    Posts:
    19
    Hi! I'm a new programmer and unity user and I am trying to make a quick game where you play a bouncing ninja fighting of incoming enemies in a simple 2D scene.

    Problem:

    I have attached a bouncy 2D physics material to my Rigidbody2D on my player character and when I don't have any script attached it works fine. But as soon as I enable the player script which is following:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     Rigidbody2D rb2d;
    8.  
    9.     public float speed = 3.0f;
    10.     float horizontal;
    11.     float vertical;
    12.  
    13.     public float jumpForce = 2000f;
    14.  
    15.     void Start()
    16.     {
    17.         rb2d = GetComponent<Rigidbody2D>();
    18.     }
    19.  
    20.     void Update()
    21.     {
    22.         horizontal = Input.GetAxis("Horizontal");
    23.         vertical = Input.GetAxis("Vertical");
    24.  
    25.         if (Input.GetKeyDown(KeyCode.Space))
    26.         {
    27.             Jump();
    28.         }
    29.  
    30.     }
    31.  
    32.     void FixedUpdate()
    33.     {
    34.         Vector2 position = rb2d.position;
    35.         position.x += speed * horizontal * Time.deltaTime;
    36.         position.y += speed * vertical * Time.deltaTime;
    37.  
    38.         rb2d.MovePosition(position);
    39.  
    40.     }
    41.  
    42.     void Jump()
    43.     {
    44.             GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpForce);
    45.      
    46.     }
    47. }
    My character goes from bouncing smoothly in an even pace to slowly falling down and then staying put to the ground like this when I enable the above script:
     
  2. Mooxe

    Mooxe

    Joined:
    Sep 18, 2013
    Posts:
    19
    Correct me if I'm wrong but I don't think you need the Vector2 "position" to calculate your movement on the y-axis,
    since you have the jump function. So maybe commenting part out could help.

    Code (CSharp):
    1. //position.y += speed * vertical * Time.deltaTime;