Question by
Aterox_os · Mar 28, 2021 at 03:06 PM ·
c#2dmovementoncollisionenter
Unity 2D jump "fly"
Hey, I've programmed a simple movement script in 2D. I've tagged the objects with "ground" and add an OnCollisionEnter2D to avoid "flying". But the script dont work. Any ideas why?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 15f;
public bool isJumping;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Jump();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
private void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "ground")
{
isJumping = true;
}
}
void Jump()
{
if (Input.GetButtonDown("Jump") && isJumping == true)
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Stepping on game object moves quickly to react 0 Answers
How to move the player only 1 tile per buttonPress? 2 Answers
2D Object following the cursor without glitchyness at the center 0 Answers
How to move an object on a moving platform with the platform 0 Answers
Player loses momentum when landing 0 Answers