I have a script that should move a platform between 2 positions.
The platform moves to pos1 but then just stops....
Here is my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platform : MonoBehaviour
{
public Transform pos1, pos2;
public float speed;
public Transform startPos;
Vector3 nextPos;
// Start is called before the first frame update
void Start()
{
nextPos = pos1.position;
}
// Update is called once per frame
void Update()
{
if (transform.position == pos1.position)
{
nextPos = pos2.position;
}
if (transform.position == pos2.position)
{
nextPos = pos1.position;
}
transform.position = Vector3.MoveTowards(transform.position, nextPos, speed * Time.deltaTime);
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(pos1.position, pos2.position);
}
}
You're setting it sequentially, so it's always going to be the second option.
In one case if nextpos is in position 1, it'll be set to position 2, but is then immediately changed again as
if nextpos is in position 2, it'll be set back to 1.
easy change should be just to change the second if statement to an else if
paraphrasing the code, but hopefully it makes sense
Related
I am making my first foray into AI, specifically AI that will follow the player.
I am using the A* Path finding project scripts, but used the Brackeys tutorial for the code
https://www.youtube.com/watch?v=jvtFUfJ6CP8
Source in case needed.
Here's the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class EnemyAI : MonoBehaviour
{
public Transform Target;
public float speed = 200f;
public float NextWayPointDistance = 3f;
Path path;
int currentWaypoint = 0;
bool ReachedEndOfpath = false;
Seeker seeker;
Rigidbody2D rb;
public Transform EnemyGraphics;
// Start is called before the first frame update
void Start()
{
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("UpdatePath", 0f, 1f);
}
void UpdatePath()
{
if (seeker.IsDone())
seeker.StartPath(rb.position, Target.position, OnPathComplete);
}
void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
// Update is called once per frame
void fixedUpdate()
{
if(path == null)
return;
if(currentWaypoint >= path.vectorPath.Count)
{
ReachedEndOfpath = true;
return;
}
else
{
ReachedEndOfpath = false;
}
Vector2 Direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
Vector2 Force = Direction * speed * Time.fixedDeltaTime;
rb.AddForce(Force);
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if(distance < NextWayPointDistance)
{
currentWaypoint++;
}
if(rb.velocity.x >= 0.01f)
{
EnemyGraphics.localScale = new Vector3(-1f, 1f, 1f);
}else if(rb.velocity.x <= 0.01f)
{
EnemyGraphics.localScale = new Vector3(1f, 1f, 1f);
}
}
}
How I tried to fix the issue:
I thought it could've been a problem with the speed so I increased it to 10000000, and still nothing
Next I thought it was a problem with the Rigidbody2d so I check there, found the gravity scale was set at 0, so I increased it to 1. It made my enemy fall to the ground but still no movement.
I thought it could've been a problem with the mass and drag, so I set Linear drag and Angular drag to 0, and also set mass to 1. Still nothing.
I set the body type to kinematic, pressed run, nothing. Set the body type to static, pressed run, nothing. Set the body type to Dynamic, pressed run, still nothing.
I tried to make a new target for the enemy to follow, dragged the empty game object i nto the target, pressed run and still didn't move.
I am at a loss on how to fix this.
Please help?
Looks like maybe a typo? You have:
// Update is called once per frame
void fixedUpdate()
{
but the method is called FixedUpdate(), with a big F in front. You have fixedUpdate, which is NOT the same.
I can't solve this problem where i want to hide and unhide a gameobject(UI) when i move using a VR controller. It came out fine in the editor but after build for the oculus quest(android), it stays inactive. anyone can help me? i put a list of UI that need to be hidden and wanted to set it active when the camera is not moving and hide when it is moving
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.UI;
public class ContinuousMovement : MonoBehaviour
{
//This script is used to make the VR Camera moves continuous using the analog
public float speed = 1;
public XRNode inputSource;
public float gravity = -9.81f;
public LayerMask groundLayer;
public float additionalHeight = 0.2f;
public List<GameObject> UiToBeHidden;
private float fallingSpeed;
private XRRig rig;
private Vector2 inputAxis;
private CharacterController character;
// Start is called before the first frame update
void Start()
{
character = GetComponent<CharacterController>();
rig = GetComponent<XRRig>();
foreach (GameObject ui in UiToBeHidden)
{
ui.SetActive(true);
}
}
// Update is called once per frame
void Update()
{
CapsuleFollowHeadset();
InputDevice device = InputDevices.GetDeviceAtXRNode(inputSource);
device.TryGetFeatureValue(CommonUsages.primary2DAxis, out inputAxis);
Quaternion headYaw = Quaternion.Euler(0, rig.cameraGameObject.transform.eulerAngles.y, 0);
Vector3 direction = headYaw * new Vector3(inputAxis.x, 0, inputAxis.y);
character.Move(direction * Time.fixedDeltaTime * speed);
if (inputAxis.x == 0 && inputAxis.y == 0)
{
Debug.Log("static");
foreach (GameObject ui in UiToBeHidden)
{
ui.SetActive(true);
}
}
else
{
Debug.Log("moving");
foreach (GameObject ui in UiToBeHidden)
{
ui.SetActive(false);
}
}
}
private void FixedUpdate()
{
//gravity
bool isGrounded = CheckIfGrounded();
if (isGrounded)
fallingSpeed = 0;
else
fallingSpeed += gravity * Time.fixedDeltaTime;
character.Move(Vector3.up * fallingSpeed * Time.fixedDeltaTime);
}
void CapsuleFollowHeadset()
{
character.height = rig.cameraInRigSpaceHeight + additionalHeight;
Vector3 capsuleCenter = transform.InverseTransformPoint(rig.cameraGameObject.transform.position);
character.center = new Vector3(capsuleCenter.x, character.height /2 + character.skinWidth, capsuleCenter.z);
}
bool CheckIfGrounded()
{
//tells us if on ground
Vector3 rayStart = transform.TransformPoint(character.center);
float rayLength = character.center.y + 0.01f;
bool hasHit = Physics.SphereCast(rayStart, character.radius, Vector3.down, out RaycastHit hitInfo, rayLength, groundLayer);
return hasHit;
}
}
I had exactly the same problem. The solution that works for me is changing the build setting.
Build Setting --> Player Settings --> Player --> Other Setting --> Api Compatibility level ( Change from .Net Standard 2.0 --> .Net 4.x)
That should work for you as well!
So there is the code with my Character's Rigidbody2D attachment, but he does not move when is set to Kinematic (working only on Dynamic), but I want Kinematic because he collides with Dynamic Objects and i didn't want him to move just left and right on touch.
UI: I'm very beginner, I just want to make my first game for Android and sorry for my english too. :D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
//variables
public float moveSpeed = 300;
public GameObject character;
private Rigidbody2D characterBody;
private float ScreenWidth;
// Use this for initialization
void Start()
{
ScreenWidth = Screen.width;
characterBody = character.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
int i = 0;
//loop over every touch found
while (i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2)
{
//move right
RunCharacter(1.0f);
}
if (Input.GetTouch(i).position.x < ScreenWidth / 2)
{
//move left
RunCharacter(-1.0f);
}
++i;
}
}
void FixedUpdate()
{
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
}
private void RunCharacter(float horizontalInput)
{
//move player
characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
}
}
From Unity docs,
If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore.
So instead of applying a force, just change it's position. Something like this:
private void RunCharacter(float horizontalInput)
{
//move player
characterBody.transform.position += new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0);
}
/*I am making a 2d game in Unity that works similarly to billiards, but with other aspects. When the player holds down button 0, a line drags away from the ball to show the direction and speed the ball will be hit off in. I don't know how to set that velocity or how to add a force like that.
I've tried setting the velocity directly, then adding fake frictions, but that didn't work too well. I also tried adding a force to the ball, and also making an empty game object that follows the pointer with a point effecter to repel the ball. But I cant seem to get anything to work.
--Also I apologize for the messy code, i'm still kinda new to this
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineDrawer : MonoBehaviour
{
public Transform tr; //this is the transform and rigid body 2d of the
ball
public Rigidbody2D rb;
public LineRenderer line; // the line rendered is on the ball
public float hitForce = 10;
// Start is called before the first frame update
void Start()
{
line = GetComponent<LineRenderer>();
line.SetColors(Color.black, Color.white);
}
// Update is called once per frame
void FixedUpdate()
{
line.SetPosition(0, tr.position - new Vector3(0, 0, 0));
if (Input.GetMouseButton(0)&&PlayerPrefs.GetInt("Moving")==0)
{
line.SetWidth(.25f, .25f);
line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));
float len = Vector2.Distance(line.GetPosition(0), line.GetPosition(1)); //this is for determining the power of the hit
}
else
{
line.SetWidth(0, 0); //make the line invisible
}
if (Input.GetMouseButtonUp(0) && (PlayerPrefs.GetInt("Moving")==0))
{
Vector2.Distance(Input.mousePosition, tr.position)*100;
Debug.Log("Up");
rb.velocity = //this is what i cant work out
PlayerPrefs.SetInt("Moving", 1);
}
}
}
//5 lines from the bottom is where i'm setting the velocity.
Just rewrite your script to the following:
using UnityEngine;
public class Ball : MonoBehaviour
{
private LineRenderer line;
private Rigidbody2D rb;
void Start()
{
line = GetComponent<LineRenderer>();
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
line.SetPosition(0, transform.position);
if (Input.GetMouseButton(0))
{
line.startWidth = .05f;
line.endWidth = .05f;
line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));
}
else
{
line.startWidth = 0;
line.endWidth = 0;
}
if (Input.GetMouseButtonUp(0))
{
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
direction.Normalize();
rb.AddForce(direction * 3f, ForceMode2D.Impulse);
}
}
}
I am trying to allow the player, in a pong game, to control both paddles. However, for some reason only one paddle is controllable while the other simply does nothing. Here is an image of the paddle property bar.
And here is the code to the right most paddle that should be controlled with arrow keys.
using UnityEngine;
using System.Collections;
public class PaddleRight : MonoBehaviour
{
public Vector3 playerPosR;
public float paddleSpeed = 1F;
public float yClamp;
void Start()
{
}
// Update is alled once per frame
void Update()
{
float yPos = gameObject.transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow)) {
playerPosR = new Vector3(gameObject.transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
print("right padddle trying to move");
}
gameObject.transform.position = playerPosR;
}
}
I can't seem to figure out anywhere why it won't move.. Please, any help would be awesome because I have checked everywhere at this point. Thanks!
I recreated the problem in a project and found that the only problem with it might be you forgetting that the yClamp is public and its set to 0 in the inspector. Make sure you set yClamp to whatever it should be instead of 0.
I would suggest moving the yPos assignment as well as setting the position inside the if statement as you arent changing those if the player isnt moving.
You can also change gameObject.transform.position to just plain transform.position
here is the refined code:
public Vector3 playerPosR;
public float paddleSpeed = 1F;
public float yClamp; // make sure it's not 0 in the inspector!
// Update is alled once per frame
void Update()
{
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow))
{
float yPos = transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);
playerPosR = new Vector3(transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
transform.position = playerPosR;
}
}