Here is my character controller code.
public float speed;
float Velocity;
public float jump;
void Update ()
{
Velocity = 0;
if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A))
{
Velocity = -speed;
}
if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D))
{
Velocity = speed;
}
if (Input.GetKey (KeyCode.UpArrow) || Input.GetKey("space") || Input.GetKey (KeyCode.W))
{
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x,
jump);
}
GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveVelocity, GetComponent<Rigidbody2D>
().velocity.y);
}
}
This is a very simple movement code
here is my cam follow code i got from Brackeys
I am having an infinte jump problem with the code and i do not know what to do to fix it
I do not know the correct syntax yet to stop it.
I am using Unity 2019.4.2f1 and VScode 2020.
Im not sure if adding what versions I use will help
but I am always getting compiler errors saying that stuff does not exist in the current context but i do not know anything else that does exist in the current context that will work.
void Update()
{
transform.position = playerPos.position + offset;
}
To fix infinite jump, use Input.GetKeyDown(KeyCode.UpArrow) instead of Input.GetKey(KeyCode.UpArrow). The GetKey function is for checking when a key is held down. the GetKeyDown function is for getting the first time the key is pressed.
Related
I am trying to make a game in Unity and I am stuck in a part where I am trying to move a platform from Point A to Point B.
The error I get is:
NullReferenceException: Object reference not set to an instance of an object
MovingPlatform.Update () (at Assets/Scripts/MovingPlatform.cs:30)
The Source Code is:
public class MovingPlatform : MonoBehaviour
{
[SerializeField]
private Transform pointA, pointB;
private float speed = 1.0f;
private Transform target;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position == pointA.position)
{
target = pointB;
}
else if (transform.position == pointB.position)
{
target = pointA;
}
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
What should I do?
Because the platform is not moving at all.
The error tells you whats wrong. In line 30 of your script you have a reference somewhere which is null (hence NullReferenceException) and you try to do something with this (e.g. accessing attributes). I guess its target.position from
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
when your if-statements dont trigger. You should add target = pointB; in Start()
to have target properly initialized (i assume you want start out moving to pointB).
I'm trying to make my square jump in Unity 2D when I press Space button. I have the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed;
public float jumpSpeed;
float moveX;
Vector2 pos;
// Update is called once per frame
void Update()
{
MoveHorizontally();
Jump();
}
void MoveHorizontally(){
moveX = Input.GetAxis("Horizontal") * Time.deltaTime;
pos.x = moveX * moveSpeed;
transform.position = new Vector2(transform.position.x + pos.x,transform.position.y + pos.y);
}
void Jump(){
if (Input.GetKeyDown("space")){
GetComponent<Rigidbody2D>().AddForce(new Vector2(0,jumpSpeed * Time.deltaTime), ForceMode2D.Impulse);
Debug.Log("Jumped!");
}
}
}
When I press Space button, "Jumped!" message shows up, but my square not jumping. Any idea?
Thanks a lot.
I tried using Input.GetKey function. It works, but that function keeps making my square go upwards if i keep holding Space button.
U need to assing a value to jumpforce. and of course to the moveforce. if u dont wanna jump repeatly Just name a bool for checking if u are on ground. I use mine as" private bool = isGrounded".
and try the code below. It makes ur jump a condition as a function of touching ground.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
isGrounded = true;
}
and here is my code for jump.
public void PlayerJump() {
if (Input.GetButtonDown("Jump") && isGrounded) {
isGrounded = false;
myBody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
whenever u jump it makes your bool variant false and whenever u touch ground it make ur bool true.
Make sure "Ground" must be same exactly the tag your ground has.
When you call AddForce() method you don't have to multiply with "Time.deltaTime".
What you can do is the following:
First cached your "Rigidbody2D" component from your Start() method because if you call it every frame it will affect your game performance.
private Rigidbody2D rigidbody2D;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
}
Second, instead of Update() method you should call the FixedUpdate() method which is recommended when you deal with Physics
void FixedUpdate()
{
MoveHorizontally();
Jump();
}
Third, on your Jump() method as I said on top you should not multiply the jump force with Time.deltaTime, instead do the following:
public float jumpForce = 10f;
public void Jump()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rigidbody2D.AddForce(Vector2.up*jumpForce);
}
}
You can adjust the jumpForce as you want.
Also Vector2.up is a shorthand for writing Vector2(0, 1)
You can read more about Vector2 here Vector2.up Unity's Documentation
I have this code:
public class MoveCard : MonoBehaviour
{
public float speed = 1f;
public Rigidbody2D rb;
public Vector2 pos = new Vector2(6.8f,0);
public bool move = false;
void FixedUpdate(){
if (move){
//Stops Rigidbody
if (rb.position == pos){
move = false;
}
rb.transform.position += -rb.transform.right * speed * Time.fixedDeltaTime;
}
}
public void CardMovement(){
move = true;
}
}
I have it set as so when a button is pressed, CardMovement() initiates and in FixedUpdate I have a if statement that turns move off when the Rigidbody reaches a certain position. The rb moves but it doesn't stop when it reaches the Vector2. I am new to Unity so I don't know if this is the way to do it.
Well your Rb doesn't pass exactly for each point between the initial position and Vector2.
It's prtty unlikely to have rb.position == pos because one frame it will not enough, and the next one will be too much :)
Try with MoveTowards. Some like this:
rb.position = Vector3.MoveTowards(rb.position, pos, speed * Time.fixedDeltaTime);
You dont need a statement to stop it because it will do it when reaches pos.
PD: You can do this with transform instead of rigidbody if u are not going to use physics and you only want a movement.
Don't compare the 2 vector2D values like this:
if(rb.position == pos)
Rather compare the distance between them with a value that is very small, like this:
if(Vector2.Distance(rb.position,pos) <= 0.01)
Additionally, you can set the position like this rb.postion = pos; if it is close enough so that it snaps to the right location.
(This is 2D project)
My character need to run left and right and jump on ground. It is my first experience with Unity and it latest available version of it, I manage to make my Character run left and right and flip when it is change direction, but it does not jump at all.
For the Character I am currently using 2 Box Collider 2Ds and Rigidbody 2D. Character has mass equal 1.
For the Ground I am currently using 2 Box Collider 2Ds. Ground is single sprite which is cover bottom part of screen.
Below is the code for jumping and grounded I am currently trying to use.
'''
{
public float maxSpeed = 10f;
public float jumpVelocity = 10f;
private bool isGrounded;
private float move = 0f;
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
private SpriteRenderer sprt_render;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
isGrounded = true;
}
// Update is called once per frame
void Update()
{
GetInput();
}
private void GetInput()
{
move = Input.GetAxis("Horizontal");
if (transform.position.x > -6.2 && transform.position.x < 5.7)
{
rb2d.velocity = new Vector2(move * maxSpeed, rb2d.velocity.y);
}
else
{
rb2d.velocity = new Vector2(move * maxSpeed * -1, rb2d.velocity.y);
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
Debug.Log("Jump");
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpVelocity);
isGrounded = false;
//rb2d.AddForce(Vector2.up * jumpVelocity, ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
'''
As you can see I try to use two different approach in connection with jump realisation using Velocity and using AddForce result is totally the same it is not jumping even first time. I check thought breakpoint it definitely go trough jumping code but nothing happened.
My character's jump is working fine in a straight line collider, then I noticed that when every-time my character jumps in a curve shape collider, my jump always turns too strong abnormaly. How can I fix this? I'll provide my initial code for jump movement below.
Here is the img :
Here is jump code:
float checkgroundradius = 0.50f;
public bool isgrounded2;
public Transform grouncheckslot;
public LayerMask LM;
public float JumpPower;
public float movespeed;
Rigidbody2d RB;
void Update () {
if (isgrounded && Input.GetKeyDown(KeyCode.UpArrow))
{
isgrounded = false;
jumping = true;
myanim.SetBool("groundedanim", isgrounded);
myrb.AddForce(new Vector2(0, jumpower));
}
}
void FixedUpdate()
{
isgrounded = Physics2D.OverlapCircle(checkslot.position, groundradius, LM);
myanim.SetBool("groundedanim", isgrounded);
myanim.SetFloat("verticalspeed", myrb.velocity.y);
float move = Input.GetAxis ("Horizontal");
RB.velocity = new Vector 2 (move * movespeed, RB.velocity.y);
}
When jumping up the slope, your Physics2D.OverlapCircle intersects with the slope, thus making isgrounded=true, making you apply more force if the UpArrow is pressed.
Once solution could be to check that your character is not already moving upwards before jumping
if (isgrounded && Input.GetKeyDown(KeyCode.UpArrow) && myrb.velocity.y <= 0.0f)
this way you wont jump again if you are already heading upwards.
Maybe you could play around with a smaller groundradius and/or try moving the checkslot.position in a way that it doesnt intersect with the slope in the same manner.
For jumping people use Rigidbody2D.AddForce with Forcemode.Impulse.
Also, change
if (isgrounded && Input.GetKeyDown(KeyCode.UpArrow))
to
if (Input.GetKeyDown(KeyCode.UpArrow) && myrb.velocity.y == 0)
So you don't need to bool isgrounded
I hope it helps you :)