没用raycast投射,使用碰撞检测函数实现了一个平台的小开关
效果是这样的
有点其实也可以不这么复杂的,但是我想起来raycast的时候已经做完了,我还想做点其他的东西,就这样写了
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class platformController : MonoBehaviour
{
// Start is called before the first frame update
public GameObject crate;//存放第一个停泊点的位置
public GameObject crate1;//第二个
public GameObject platform;//平台
public float speed;
public bool isDown;//开关状态
public bool Trigger = false;//检测是否站在了开关点
Animator animator;
public float TriggerTime = 3.0f;
private float Timer;
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Timer > 0)
{
if (Input.GetKeyDown(KeyCode.V))
{
isDown = !isDown;
}
Timer -= Time.deltaTime;
}
else Trigger = false;
if (isDown)//如果开关下拉平台往右走,上拉往左走
{
Vector2 position = new Vector2(crate1.transform.position.x - 5, platform.transform.position.y);
Move(position, Time.deltaTime);
}
else
{
Vector2 position = new Vector2(crate.transform.position.x + 5, platform.transform.position.y);
Move(position, Time.deltaTime);
}
if (isDown)
animator.SetBool("down", true);
else animator.SetBool("down", false);
}
private void Move(Vector2 position,float dt)//移动
{
platform.transform.position = Vector2.MoveTowards(platform.transform.position, position, dt * speed);
}
private void OnTriggerEnter2D(Collider2D other)
{
foxcontroller fox = other.gameObject.GetComponent<foxcontroller>();
if (fox != null)//碰撞成功开始计时
{
Trigger = true;
Timer = TriggerTime;
}
}
}
我这一套写了很多不必要的步骤,全部是按自己的编程习惯来的,有点子复杂与麻烦,还有些漏洞,不过也算是提供一点不那么好的思路吧,可以看一下。
第二个我是写了一个具有特殊效果的奇异果
吃了以后开启超级跳模式,无限跳跃次数,体验上天的感觉
效果是这样的
吃果子之前是这样的
弱,太弱了,所以我们得多寻找这样的奇迹之果(bushi)
代码是这样的
private void superJump()//这里超级跳跃模式
{
if (Input.GetKeyDown(KeyCode.Space))
{
isjump = true;
rb2d.velocity = Vector2.up * jumpForce;//添加力
jumpTime = jumpStartTime;
}
if(Input.GetKey(KeyCode.Space)&&isjump == true)//甚至还有长跳
{
if(jumpTime > 0)
{
rb2d.velocity = Vector2.up * jumpForce;
jumpTime -= Time.deltaTime;
}
}
else
{
isjump = false;
}
if (Input.GetKeyUp(KeyCode.Space))
{
isjump = false;
}
}
void normalJump()
{
if (Input.GetKeyDown(KeyCode.Space)&&jump>1)
{
rb2d.velocity = Vector2.up * jumpForce;
jump--;
}
if (isGround)//落地刷新跳跃次数
{
jump = jumpNumber;
}
}
if (canSuperJumpTime > 0)//这里是控制,剩余超级跳时间
{
canSuperJumpTime -= Time.deltaTime;
canSuperJump = true;
}
else canSuperJump = false;
if (canSuperJump)
{
superJump();
}
else normalJump();
public class superJump : MonoBehaviour
{
// Start is called before the first frame update
public float canSuperJumpTime;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
foxcontroller fox = other.GetComponent<foxcontroller>();
if (fox != null)
{
fox.canSuperJumpTime = canSuperJumpTime;
}
Destroy(gameObject);
}
}
果子的代码很简单,触发器触发以后给角色一个超级跳时间就行了