问题描述
因此,我正在使用此功能,该功能可以使汽车变道。只要我不退回车牌return vehicleObject_list[i]
,它就会改变车道。但是,当我按照说明要求退回车牌时,汽车停止更改车道return vehicleObject_list[i].Number_Plate
。详细信息如下:
function moveLanes(target_car)
{
/*
This function should do the following:
- move target_car from one lane to the other.
- do the move in a single step without any extra animation.
- use Lane_Position_a and Lane_Position_b to effect the change.
- finally you should return target_car at the end of the function.
hint: You will need to modify the x property of target_car.
*/
if(checkCarInfront(target_car).x == Lane_Position_a ){
target_car.x = Lane_Position_b;
}
else {
target_car.x = Lane_Position_a;
}
}
function checkCarInfront( carObj )
{
/*
This function should do the following:
- determine if carObj is in the same lane and less than 200px behind any of the cars in vehicleObject_list.
- do this by traversing vehicleObject_list and comparing each car's distance_Driven property to that of carObj.
- if you find a car that matches these requirements then return the Number_Plate property for the car. Otherwise return false.
*/
for (var i = 0; i < vehicleObject_list.length; i++)
{
if (carObj.x == vehicleObject_list[i].x && ((vehicleObject_list[i].distance_Driven - carObj.distance_Driven) < 200) && ((vehicleObject_list[i].distance_Driven - carObj.distance_Driven) > 0))
{
return vehicleObject_list[i].Number_Plate;
}
}
return false;
}
var vehicleObject_list = [
{ x: 500,y: 0,distance_Driven: -200,Car_Type: 'greenCar',Number_Plate: 'MBH0WW',Gas_Amt: 2,exhaust: [ ]},{ x: 500,distance_Driven: 200,Car_Type: 'whiteCar',Number_Plate: 'RLDGCM',{ x: 300,distance_Driven: 600,Number_Plate: '9WGXXI',exhaust: [ ]} ]
Detective_CarObject =
{
x: roadLeftEdge + roadWidth/4,y: 550,distance_Driven: 0,Gas_Amt: 3,Engineshudder_Value: 0,Car_Type: 'detective',Number_Plate: '5L3UTH',exhaust: []
}
解决方法
您可以执行以下操作:
if(checkCarInfront(target_car) && target_car.x == Lane_Position_a ){
target_car.x = Lane_Position_b;
} else {
target_car.x = Lane_Position_a;
}
因为checkCarInfront(target_car)
将在存在匹配项的情况下返回一个车牌字符串(该字符串将作为非空字符串求值为true)。您可以将条件链接到具有target_car
属性的.x
对象。
请确保手动测试数据。 (例如,如果调用vehicleObject_list
,则使用当前的Detective_CarObject
和checkCarInfront(Detective_CarObject)
值,这将是错误的(由于Distance_Driven
)。不过,您可以临时设置{{1} } x到Detective_CarObject
,并在列表中添加额外的测试车以检查您的逻辑:500
)
作为旁注,我建议遵循JS命名约定。以下是几个示例:W3Schools,FreeCodeCamp,Google JavaScript Style Guide。
过去我会说选择一个(例如,下划线/ snake_case(例如,{ x: 500,y: 0,Distance_Driven: 199,Car_Type: 'rainbowCar',Number_Plate: 'R41NB0W',Gas_Amt: 2,exhaust: [ ]}
)或camelCase(例如,target_cat
),但不能同时选择两者并保持一致,但如今看来大多数人坚持骆驼的情况。这样做将使以后的团队工作和共享/贡献开源库和项目变得更加容易。