So I have been trying to figure out how to something for movement with balls. I managed to create a script that works for one ball, but I am trying to implement a split keyboard feature. I need help so I can control two things with the same script and different keys… I did use horizontal and vertical get axis keys which is my main issue. Im trying to get the second ball to move with the keys
8
4 5 6 on the number pad
The code I used is below
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float BallSpeed;
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
GetComponent<Rigidbody>().AddForce(movement * BallSpeed);
}
}
You can do this by loading a reference to your other object in your first object’s script and then detecting input with Input.GetKey along with KeyCode.Keypad#. There’s also a couple things you could do to improve general performance. Here’s an example of what an implementation of the second ball’s movement might look like:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float ballSpeed = 1f;
private GameObject secondBall;
private Rigidbody thisRigidbody;
private Rigidbody secondRigidbody;
private float moveHorizontal;
private float moveVertical;
void Start()
{
//This is a GameObject named SecondBall in your Resources folder
secondBall = Resources.Load("SecondBall") as GameObject;
//Stores Rigidbodys in local variables so you don't have to get them every Update
thisRigidbody = GetComponent<Rigidbody>();
secondRigidbody = secondBall.GetComponent<Rigidbody>();
}
void FixedUpdate()
{
moveHorizontal = Input.GetAxis("Horizontal");
moveVertical = Input.GetAxis("Vertical");
thisRigidbody.AddForce(new Vector3(moveHorizontal, 0.0f, moveVertical) * ballSpeed);
//Horizontal keypad movement
if (Input.GetKey(KeyCode.Keypad4) && !Input.GetKey(KeyCode.Keypad6))
moveHorizontal = -1f;
else if (Input.GetKey(KeyCode.Keypad6) && !Input.GetKey(KeyCode.Keypad4))
moveHorizontal = 1f;
else
moveHorizontal = 0f;
//Vertical keypad movement
if (Input.GetKey(KeyCode.Keypad8) && !Input.GetKey(KeyCode.Keypad5))
moveVertical = 1f;
else if (Input.GetKey(KeyCode.Keypad5) && !Input.GetKey(KeyCode.Keypad8))
moveVertical = -1f;
else
moveVertical = 0f;
secondRigidbody.AddForce(new Vector3(moveHorizontal, 0.0f, moveVertical) * ballSpeed);
}
}