GetComponent requires that the requested component ‘JointMotor2D’ derives from MonoBehaviour or Component or is an interface.
UnityEngine.GameObject.GetComponent[JointMotor2D] () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/GameObjectBindings.gen.cs:38)
Paddle.Start () (at Assets/Paddle.cs:12)
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Paddle : MonoBehaviour {
private Rigidbody2D rb2d;
private JointMotor2D motor;
public float speed = -100;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D> ();
motor = GetComponent<JointMotor2D> ();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("left"))
motor.motorSpeed = speed;
}
void FixedUpdate ()
{
}
}
I think you may have this all wrong. A JointMotor2D is a component of a component. So if you have a reference to a joint type component then you can say
motorRef = jointRef.motor;
You can’t even call it “motor” that would be illegal.
motorSpeed is just the speed you want a rigidbody that is connected to the joint to reach if the joint is moving.
So you need to get an object other than the objectyou want to move. Add a joint to it. Then in the inspector for that joint you can add your other object that has a rigidbody to it’s connected rigidbody field. Now when you want that thing to move you can move the joint instead. The motorSpeed will limit how fast that thing will actually move.
I think you should search tutorials on joints and motors.
Ok, so I did some tinkering with the code you have so far and I got something close to what you are going for think. I am not sure how to directly change the Motor Speed from inside the script, however using “.maxTorque” and changing the speed variables when the are pressed down seems to work; especially when you change between “.useMotor = true” and “.useMotor = false” before each change.
I have yet to clean up the code, so there is probably a far simpler way to do this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveLimbOnButtonDWN : MonoBehaviour {
public Rigidbody2D rb2d;
private HingeJoint2D jointRef;
private JointMotor2D motorRef;
public float speed = 200;
void Start () {
rb2d = GetComponent<Rigidbody2D> ();
jointRef = GetComponent<HingeJoint2D> ();
motorRef = jointRef.motor;
jointRef.useMotor = false;
print(motorRef.maxMotorTorque);
}
void Update () {
if (Input.GetKey (KeyCode.A)) {
motorRef.motorSpeed = speed;
motorRef.maxMotorTorque = 100;
jointRef.useMotor = true;
print(motorRef.maxMotorTorque);
//Trying to create opposite effect and stop movement (doesn't work as hoped)
} if (Input.GetKeyUp (KeyCode.D)) {
jointRef.useMotor = false;
motorRef.maxMotorTorque = 0;
print(motorRef.maxMotorTorque);
}
}
}
Hopefully this has helped a bit. I am hoping someone else can make this even more streamlined for everyone.