Unity3D standard asset script not functioning properly - c#

I am trying to complete a project using unity3D standard assets. But while importing the assets the scripts were creating an error - "No MonoBehavior scripts in the file, or their names do not match the file name." and another error - "Assets\Standard Assets\Characters\RollerBall\Scripts\BallUserControl.cs(3,27): error CS0234: The type or namespace name 'CrossPlatformInput' does not exist in the namespace 'UnityStandardAssets' (are you missing an assembly reference?)". As I am new to unity and although I have prior knowledge but not in C# I am not understanding the errors. I have also given a script below for finding the problem.
using System;
using UnityEngine;
namespace UnityStandardAssets.Vehicles.Ball
{
public class Ball : MonoBehaviour
{
[SerializeField] private float m_MovePower = 5; // The force added to the ball to move it.
[SerializeField] private bool m_UseTorque = true; // Whether or not to use torque to move the ball.
[SerializeField] private float m_MaxAngularVelocity = 25; // The maximum velocity the ball can rotate at.
[SerializeField] private float m_JumpPower = 2; // The force added to the ball when it jumps.
private const float k_GroundRayLength = 1f; // The length of the ray to check if the ball is grounded.
private Rigidbody m_Rigidbody;
private void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
// Set the maximum angular velocity.
GetComponent<Rigidbody>().maxAngularVelocity = m_MaxAngularVelocity;
}
public void Move(Vector3 moveDirection, bool jump)
{
// If using torque to rotate the ball...
if (m_UseTorque)
{
// ... add torque around the axis defined by the move direction.
m_Rigidbody.AddTorque(new Vector3(moveDirection.z, 0, -moveDirection.x)*m_MovePower);
}
else
{
// Otherwise add force in the move direction.
m_Rigidbody.AddForce(moveDirection*m_MovePower);
}
// If on the ground and jump is pressed...
if (Physics.Raycast(transform.position, -Vector3.up, k_GroundRayLength) && jump)
{
// ... add force in upwards.
m_Rigidbody.AddForce(Vector3.up*m_JumpPower, ForceMode.Impulse);
}
}
}
}

Related

In unity 2D after applying force to a rigid body how do I make it rotate to face the direction of travel

new to all this. I've tried following a few examples i've found on here but none seem to work. The best I have right now is
rb.transform.up = rb.GetComponent<Rigidbody2D>().velocity.normalized;
but this makes the rigid body rotate immediately to the new direction of travel. is there a way to make it so it rotates slower rather than jumping in one frame to the new direction of travel?
Any help would be appreciated :)
here is the code ive used to apply the force, if that matters? i got it from a tutorial to apply force based on dragging the mouse
public class DragNShoot : MonoBehaviour
{
public float power = 10f;
public Rigidbody2D rb;
public Vector2 minPower;
public Vector2 maxPower;
public TrajectoryLine tl;
Camera cam;
Vector2 force;
Vector3 startPoint;
Vector3 endPoint;
public void Start()
{
cam = Camera.main;
tl = GetComponent<TrajectoryLine>();
}
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
startPoint.z = 15;
}
if (Input.GetMouseButton(0))
{
Vector3 currentPoint = cam.ScreenToWorldPoint(Input.mousePosition);
currentPoint.z = 15;
tl.RenderLine(startPoint, currentPoint);
}
if (Input.GetMouseButtonUp(0))
{
endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
endPoint.z = 15;
force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));
rb.AddForce(force * power, ForceMode2D.Impulse);
tl.EndLine();
}
}
}
and here is script for the rotation
public class FaceDirectionOfTravel : MonoBehaviour
{
public Rigidbody2D rb;
// Update is called once per frame
void Update()
{
rb.transform.up = rb.GetComponent<Rigidbody2D>().velocity.normalized;
}
}
As you can see, I have just taken the velocity and applied that to the rotation, I guess this just immediatly changes it to match, but I want it to visibly rotate to match the rotation. I have tried some examples I have seen on here for Slerp but that only seemed to leave it in free rotation.. I must be missing something really obvious so thought I would ask on here. Thanks.
EDIT:
So I've kinda worked out a way to get it to work by creating another object on top of the object i wish to rotate and use Slerp to rotate the object on top to slowly rotate to the same as the original object which has to snap immediatly due to force applied the code is simply
public class RotateSprite : MonoBehaviour
{
[SerializeField] private Rigidbody2D rbOfTarget;
[SerializeField] private Rigidbody2D rb;
private void Start()
{
}
// Update is called once per frame
void Update()
{
rb.transform.position = rbOfTarget.transform.position;
rb.transform.rotation = Quaternion.Slerp(rb.transform.rotation, rbOfTarget.transform.rotation, 30* Time.deltaTime);
}
}
if anyone knows a better solution do let me know. Thanks.
Is your game in 3D or 2D? you keep saying it's 2D but the tag says it is 3D and if 2D you wouldn't need a Z position. and if it is in 3D you would have to change the rigidbody2D to just rigidbody.

Why can't I move my character in unity using newInput package?

I'm new to unity and I'm trying to follow this tutorial: https://www.youtube.com/watch?v=7iYWpzL9GkM&t=1600s
But when I do the code at 42:00 and compile my character wont move at all. I wont to believe I did everything exactly as the video explains but I cant figure out how to fix it.
Here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine.InputSystem;
using UnityEngine;
//Take and handle input and movement from the character
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 1f;
public float collisionOffset = 0.05f;
public ContactFilter2D movementFilter;
Vector2 movementInput;
Rigidbody2D rb;
List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate(){
//If movement input is not 0, try to move
if(movementInput != Vector2.zero){
bool success = TryMove(movementInput);
if(!success){
success = TryMove(new Vector2(movementInput.x, 0));
}
if(!success){
success = TryMove(new Vector2(0, movementInput.y));
}
}
}
private bool TryMove(Vector2 direccion){
//Check for Potencial Collisions
int count = rb.Cast(
direccion, // X and Y values between -1 and 1 that represent the direction from the body to look for collision
movementFilter, // The setting that determines where a collision can occur on such as layers to collide with
castCollisions, // Lists of collisions to store the found collisions into after the Cast is finished
moveSpeed = Time.fixedDeltaTime + collisionOffset); // The amount to cast equal to the movement plus an offset
if(count == 0){
rb.MovePosition(rb.position * direccion * moveSpeed * Time.fixedDeltaTime);
return true;
} else{
return false;
}
}
void OnMove(InputValue movementValue){
movementInput = movementValue.Get<Vector2>();
}
}
If anyone can help I really appreciate it.
Input System: version 1.3.0
Visual Studio Code Editor: version 1.2.5
Test Framework: version 1.1.33
Unity: version 2021.3.7f1
Your should change direccion to direction in TryMove.
You should make sure you have all your values in the inspector assigned to the according thing. eg. rb should be assigned to your character and your character should have the rigidBody attached to it.
Hope this helps, tell me if it still doesn't work.

Unity3D: How can i make my player go where i clicked with the mouse, without nav mesh agent?

I want to move my player around in my level without a NavMesh Agent.
I was thinking something about raycasting, but i have tried everything and even looked up videos and searched on google about it, can't seem to find anything that works
Plz help!
you can use this for moving to mouseclick position.
This method will move object or player to the position where mouse is clicked on screen.
sorry for syntax error i have typed directly here
using UnityEngine;
using System.Collections;
public class MouseMovement : MonoBehaviour
{
public float speed = 10f;
bool isplayermove = false;
// Use this for initialization
private void Start ()
{
Vector3 playerpos = transform.position;
}
// Update is called once per frame
private void Update ()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
is moveplayer = true;
}
if(ismoveplayer)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(input.mousepos.x,input.mousepos.y,input.mousepos.z);
transform.position = Vector3.MoveTowards(transform.position,new Vector3(mousepos.x,transform.position.y,mousepos.z),speed * time.deltatime);
if(transform.position == mousepos)
{
ismoveplayer = false;
}
}
}
}

Moving Game Object with UI Buttons

I am trying to set up control of Player game object by UI buttons.
2d top down view scene.
I want to transfer Player object smoothly on fixed distance (0.8 for Axix X for left-right direction and 2.4 for up-down)when I release left/right/up/down ui buttons.
Here i found code for smooth movement but there Player is moving all the time while ui button is pressed.
Can you help me to make it move on mouse up (pointer up) and to move for public x= 0.8f for left/right, and public y = 2.4f for up/down
And at the same time i want to use different speed (peblic) for moves on x and y Axis
Its ok if it should be totally other script using smth like transform.translate
Kindly guide to for any possible solution for this. Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerControl : MonoBehaviour
{
float movX;
float movY;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
movX = CrossPlatformInputManager.GetAxisRaw("Horizontal");
movY = CrossPlatformInputManager.GetAxisRaw("Vertical");
rb.velocity = new Vector2(movX * 1, movY * 1);
}
}
This script can be moved by the WASD keys.
This should move your gameObject by the requested amount over x amount of time(speed).
Currently it can be only moved when it'S reached its destionation but you can easily modify this :), by stopping the coroutine
using System.Collections;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
// We gonna move by WASD keys
[Header("Speed & Movement settings")]
[SerializeField]
float Speed = 2.0f;
[SerializeField]
float movSpeedX = 0.8f;
[SerializeField]
float movSpeedY = 2.4f;
bool ReachedTarget = true;
void Update()
{
if (ReachedTarget)
{
Vector2 dest = Vector2.zero;
Vector2 currentPos = transform.position;
if (Input.GetKeyUp(KeyCode.W))
{
dest = currentPos + (Vector2.up * movSpeedY);
StartCoroutine(moveTo(dest, Speed));
}
else if (Input.GetKeyUp(KeyCode.S))
{
dest = currentPos + (Vector2.down * movSpeedY);
StartCoroutine(moveTo(dest, Speed));
}
else if (Input.GetKeyUp(KeyCode.D))
{
dest = currentPos + (Vector2.right * movSpeedX);
StartCoroutine(moveTo(dest, Speed));
}
else if (Input.GetKeyUp(KeyCode.A))
{
dest = currentPos + (Vector2.left * movSpeedX);
StartCoroutine(moveTo(dest, Speed));
}
}
}
// Time to take is in seconds
IEnumerator moveTo(Vector2 TargetPosition, float TimetoTake)
{
Vector2 originalPosition = transform.position;
float Time_taken = 0f;
ReachedTarget = false;
while (Time_taken < 1)
{
Time_taken += Time.deltaTime / TimetoTake;
// Interpolating between the original and target position this basically provides your "speed"
transform.position = Vector2.Lerp(originalPosition, TargetPosition, Time_taken);
yield return null;
}
Time_taken = 0;
transform.position = TargetPosition;
ReachedTarget = true;
}
}
I can't find any documentation of CrossPlatformInputManager, and I know nothing about it. But if you need to get the event of "release a key" instead of "press the key", try this: Input.GetKeyUp.
Description
Returns true during the frame the user releases the key identified by
name.
You need to call this function from the Update function, since the
state gets reset each frame. It will not return true until the user
has pressed the key and released it again.
For the list of key identifiers see Conventional Game Input. When
dealing with input it is recommended to use Input.GetAxis and
Input.GetButton instead since it allows end-users to configure the
keys.
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
void Update()
{
if (Input.GetKeyUp("space"))
{
print("Space key was released");
}
}
}
If you want to stop the rigid body, you need to reset its velocity to
zero. Or you can use
Rigidbody2D.MovePosition
to move it a certain distance.
Parameters
position The new position for the Rigidbody object.
Description
Moves the rigidbody to position.
Moves the rigidbody to the specified position by calculating the
appropriate linear velocity required to move the rigidbody to that
position during the next physics update. During the move, neither
gravity or linear drag will affect the body. This causes the object to
rapidly move from the existing position, through the world, to the
specified position.
Because this feature allows a rigidbody to be moved rapidly to the
specified position through the world, any colliders attached to the
rigidbody will react as expected i.e. they will produce collisions
and/or triggers. This also means that if the colliders produce a
collision then it will affect the rigidbody movement and potentially
stop it from reaching the specified position during the next physics
update. If the rigidbody is kinematic then any collisions won't affect
the rigidbody itself and will only affect any other dynamic colliders.
2D rigidbodies have a fixed limit on how fast they can move therefore
attempting to move large distances over short time-scales can result
in the rigidbody not reaching the specified position during the next
physics update. It is recommended that you use this for relatively
small distance movements only.
It is important to understand that the actual position change will
only occur during the next physics update therefore calling this
method repeatedly without waiting for the next physics update will
result in the last call being used. For this reason, it is recommended
that it is called during the FixedUpdate callback.
Note: MovePosition is intended for use with kinematic rigidbodies.
// Move sprite bottom left to upper right. It does not stop moving.
// The Rigidbody2D gives the position for the cube.
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public Texture2D tex;
private Vector2 velocity;
private Rigidbody2D rb2D;
private Sprite mySprite;
private SpriteRenderer sr;
void Awake()
{
sr = gameObject.AddComponent<SpriteRenderer>();
rb2D = gameObject.AddComponent<Rigidbody2D>();
}
void Start()
{
mySprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f);
velocity = new Vector2(1.75f, 1.1f);
sr.color = new Color(0.9f, 0.9f, 0.0f, 1.0f);
transform.position = new Vector3(-2.0f, -2.0f, 0.0f);
sr.sprite = mySprite;
}
void FixedUpdate()
{
rb2D.MovePosition(rb2D.position + velocity * Time.fixedDeltaTime);
}
}
Both documents have an example.
Or you don't want to user keyboard but UI buttons, try this: IPointerDownHandler and IPointerUpHandler
Description
Interface to implement if you wish to receive OnPointerDown callbacks.
Detects ongoing mouse clicks until release of the mouse button. Use
IPointerUpHandler to handle the release of the mouse button.
//Attach this script to the GameObject you would like to have mouse clicks detected on
//This script outputs a message to the Console when a click is currently detected or when it is released on the GameObject with this script attached
using UnityEngine;
using UnityEngine.EventSystems;
public class Example : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
//Detect current clicks on the GameObject (the one with the script attached)
public void OnPointerDown(PointerEventData pointerEventData)
{
//Output the name of the GameObject that is being clicked
Debug.Log(name + "Game Object Click in Progress");
}
//Detect if clicks are no longer registering
public void OnPointerUp(PointerEventData pointerEventData)
{
Debug.Log(name + "No longer being clicked");
}
}

Unable to fix monobehaviour scripts problem in Unity

I was just getting started with Unity and using it's Standard Assets library. I used its rollerball object, but both its Ball and BallUserControl scripts gave me the following error:
No Monobehaviour scripts in the file, or the names do not match the file name.
I didn't change any scripts, and I have no other objects or scripts in my environment. The class names match the file names. I am sure I am missing something obvious (being so new). What are some possible errors?
I am running the latest version of unity on windows 10.
Here's the BallUserControl script, as requested:
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Vehicles.Ball
{
public class BallUserControl : MonoBehaviour
{
private Ball ball; // Reference to the ball controller.
private Vector3 move;
// the world-relative desired move direction, calculated from the camForward and user input.
private Transform cam; // A reference to the main camera in the scenes transform
private Vector3 camForward; // The current forward direction of the camera
private bool jump; // whether the jump button is currently pressed
private void Awake()
{
// Set up the reference.
ball = GetComponent<Ball>();
// get the transform of the main camera
if (Camera.main != null)
{
cam = Camera.main.transform;
}
else
{
Debug.LogWarning(
"Warning: no main camera found. Ball needs a Camera tagged \"MainCamera\", for camera-relative controls.");
// we use world-relative controls in this case, which may not be what the user wants, but hey, we warned them!
}
}
private void Update()
{
// Get the axis and jump input.
float h = CrossPlatformInputManager.GetAxis("Horizontal");
float v = CrossPlatformInputManager.GetAxis("Vertical");
jump = CrossPlatformInputManager.GetButton("Jump");
// calculate move direction
if (cam != null)
{
// calculate camera relative direction to move:
camForward = Vector3.Scale(cam.forward, new Vector3(1, 0, 1)).normalized;
move = (v*camForward + h*cam.right).normalized;
}
else
{
// we use world-relative directions in the case of no main camera
move = (v*Vector3.forward + h*Vector3.right).normalized;
}
}
private void FixedUpdate()
{
// Call the Move function of the ball controller
ball.Move(move, jump);
jump = false;
}
}
}
If monobeviour files are missing or not showing in the visual studio and creates error, Go to Edit/Preferences/External Tools/ select visual studio version and
Regenerate project files. It worked for me.

Categories

Resources