I'm trying to use the .AddForce code alongside the .movePosition one, but the .movePosition making the .AddForce do nothing. I think is because the line: " Vector2 movement = new Vector2 (moveHorizontal, 0);" but I really don't know how to fix it. The .AddForce code works as inteded by itself.
Edit: posted full code.
using UnityEngine; using System.Collections;
public class CompletePlayerController : MonoBehaviour {
public float speed; //Floating point variable to store the player's movement speed.
public float jumpforce;
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
// Use this for initialization
void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();
}
//FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
void FixedUpdate()
{
Jump();
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxis ("Horizontal");
//Store the current vertical input in the float moveVertical.
//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2 (moveHorizontal, 0);
//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
rb2d.MovePosition ((Vector2)transform.position + (movement * speed * Time.deltaTime));
}
void Jump(){
if (Input.GetButtonDown("Vertical")){
rb2d.AddForce(new Vector2(0, jumpforce), ForceMode2D.Impulse);
}
}
}
AddForce
code here. AddForce will apply a force to an object where as MovePosition will move the object using interpolation. Seems like MovePosition will simply overwrite the applied force – Derek C.