- Home /
Question by
theshaggyking347 · Jan 04 at 03:09 AM ·
c#movementgetaxis
I need help on this movement script
i need help with this script because I tried debugging it and moveHorizontal is equal to zero how can i change that here is the script below:
//setting up variables private Rigidbody2D rb2D;
private float moveSpeed;
private float jumpForce;
private bool isJumping;
private float moveHorizontal;
private float moveVertical;
void Start()
{
//defining variables
rb2D = gameObject.GetComponent<Rigidbody2D>();
moveSpeed = 3000000f;
jumpForce = 60f;
isJumping = false;
}
void Update()
{ //input for left right movement
float moveHorizontal = Input.GetAxisRaw("Horizontal");
moveVertical = Input.GetAxisRaw("Vertical");
Debug.Log("moveHorizontal " + moveHorizontal);
Debug.Log("Velocity " + rb2D.velocity.x + " " + rb2D.velocity.y);
}
void Addforce()
{
//function that adds a force to rigidbody
rb2D.AddForce(new Vector2( moveHorizontal * moveSpeed, 0f), ForceMode2D.Impulse);
}
private void FixedUpdate()
{
if (moveHorizontal > 0.1f || moveHorizontal < -0.1f)
// if moveHorizontal is greater then 0.1f or if moveHorizontal is less than -0.1f then put a force to a rigidbody
{
Addforce();
}
}
rgggh.png
(23.0 kB)
Comment
Answer by yuvaansh · Jan 04 at 05:53 AM
@theshaggyking347
I think you should do the Rb2D initialization a little differently. Like,
rb2D = GetComponent<RigidBody2D>();
//We are doing this instead of gameObject.GetComponent<RigidBody2D();
I hope this Helps :-D
Answer by unity_ZYsHk4nnsD81HQ · Jan 04 at 09:48 AM
here is my old projects movement script i hope this helps!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2D : MonoBehaviour {
public float movespeed = 13f;
public bool isGrounded = false;
void Update () {
Jump();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * movespeed;
}
void Jump(){
if (Input.GetButtonDown("Jump") && isGrounded == true)
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 20f), ForceMode2D.Impulse);
}
}
}
Your answer

Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Multiple Cars not working 1 Answer
Input.GetAxisRaw("horizontal") not working 1 Answer
Distribute terrain in zones 3 Answers
Move Object to location of Trigger? 1 Answer