I have recently been trying to learn how to make Unity games through Lynda.com using the tutorials provided by Jesse Freeman. But I have one issue, he doesn't explain any of the coding. This bit has me confused.
Body2D.AddForce (new Vector2 (forceX, forceY));
1.) Why is Body2D (this is a variable) separated by AddForce with a .?
2.) Why does a new vector2 have to be created?
3.) My last question isn't quite in the code itself but why must we add a () to methods?
(Full Code)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public float Speed = 2.5f;
public Vector2 MaxVelocity = new Vector2 (5, 10);
private Rigidbody2D Body2D;
private SpriteRenderer Renderer2D;
// Use this for initialization
void Start () {
Body2D = GetComponent<Rigidbody2D> ();
Renderer2D = GetComponent<SpriteRenderer> ();
}
// Update is called once per frame
void Update () {
var absValX = Mathf.Abs (Body2D.velocity.x);
var forceX = 0f;
var forceY = 0f;
if (Input.GetKey("right")){
if (absValX < MaxVelocity.x) {
forceX = Speed;
}
} else if (Input.GetKey("left")) {
if (absValX < MaxVelocity.x){
forceX = -Speed;
}
}
Body2D.AddForce (new Vector2 (forceX, forceY));
}